将循环的输出存储为R中的列表
我正在运行一个小循环,将数字1到30的列表随机分配给4个组的子集。我想将4个子集的循环输出作为一行存储在一个变量中,并在其他地方使用结果。我也收到一些警告,尽管输出正确显示在屏幕上将循环的输出存储为R中的列表,r,loops,random,R,Loops,Random,我正在运行一个小循环,将数字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
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
我找不到这个错误的原因。请帮忙。谢谢 使用for循环比使用while循环效果好,使用seq函数时不需要设置子变量i
list = c(6, 9, 3, 12)
start <- 1
end <- 6
for(i in seq(list)){
if(i <= list[i]){
start <- start+list[i]
end <- end + (list[i]+1)
print(sample(start:end, replace=T))
}
}
[1] 10 8 11 7 11 10 12
[1] 23 17 18 21 22 18 20 21
[1] 25 21 27 23 26 26 23 25 22
[1] 33 32 37 37 35 40 32 37 34 38
Mapfunctionstart,stop{samplestart:stop,replace=TRUE},cumsumc1,6,9,3,cumsumc6,9,3,12我试图初始化“y”,谢谢@alistaire的帮助。它仍然以四行输出。我更喜欢单线输出有两个原因:1样本量和分组非常大。因此,以m x n为单位的组的单线输出将很有帮助。2实际情况下的累积值将因此大于本例;因此,我希望将其指定为一个列表,可以对mxn数据集进行控制。再次感谢。这些警告是因为我需要澄清@dww。我会看一看。@mysqlnew在您的列表中,当您运行循环子设置I=1时,您的列表中有6,9,3,12,在最后一次迭代中,我的值为4,I=I+1变为5,其中5不小于或等于列表中的3,因此您将获得错误消息Hanks Arun以进行说明。对于大样本量来说,for循环是一个问题。@mysqlnew如果您感到抱歉,请投票支持我的答案。虽然for循环消除了错误,但它并没有多大帮助。该列表用于生成4个随机数集,它们之间不替换。输出应该像我的列表示例一样,但只在一行中生成。3 5 6 1 5 6 9 13 12 7 11 12 14 14…谢谢你的帮助,但我不能投票给你的答案@alistaire answer消除了警告,但仍然无法在一行中获得输出。谢谢大家的帮助