【发布时间】:2016-09-10 02:14:53
【问题描述】:
我正在运行一个小循环,将数字列表(1 到 30)随机分配给 4 个组的子集。我想将循环的输出(对于 4 个子集)作为一行存储在一个变量中,并在其他地方使用结果。尽管输出正确显示在屏幕上,但我也收到了一些警告。
list = as.vector(c(6, 9, 3, 12)
start <- 1
end <- 6
i <- 1
while(i<=list){
print(sample(start:end, replace=T))
start <- start+list[i]
end <- end + list[i+1]
i <- i+1
}
[1] 3 5 6 1 5 6
[1] 9 13 12 7 11 12 14 11 14
[1] 16 17 17
[1] 28 22 26 21 28 26 22 28 26 30 21 19
Error in start:end : NA/NaN argument
In addition: Warning messages:
1: In while (i <= list) { :
the condition has length > 1 and only the first element will be used
2: In while (i <= list) { :
the condition has length > 1 and only the first element will be used
3: In while (i <= list) { :
the condition has length > 1 and only the first element will be used
4: In while (i <= list) { :
the condition has length > 1 and only the first element will be used
5: In while (i <= list) { :
the condition has length > 1 and only the first element will be used
我无法找到此错误的原因。请帮忙。谢谢。
【问题讨论】:
-
Map(function(start, stop){sample(start:stop, replace = TRUE)}, cumsum(c(1,6,9,3)), cumsum(c(6,9,3,12))) -
我试图初始化'y
-
感谢@alistaire 的帮助。它仍然产生四行输出。我更喜欢单行输出,原因有两个:(1)样本量和分组非常大。因此,m x n 组的单行输出将很有帮助。 (2) 实际情况下的cumsum值会比这个例子大;因此,我希望指定为一个列表,可以针对 m x n 数据集进行控制。再次感谢。
-
警告是因为
i<=list将 i 与列表的每个元素进行比较并返回一个逻辑向量。你可能会提醒i<= length(list)。但无论如何,while 循环不是要走的路,你应该使用@alistaire 建议的矢量化方法 -
感谢@dww 的澄清。我去看看。