【问题标题】:Storing the output from a loop as a list in R将循环的输出存储为R中的列表
【发布时间】: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&lt;=list 将 i 与列表的每个元素进行比较并返回一个逻辑向量。你可能会提醒i&lt;= length(list)。但无论如何,while 循环不是要走的路,你应该使用@alistaire 建议的矢量化方法
  • 感谢@dww 的澄清。我去看看。

标签: r loops random


【解决方案1】:

使用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

【讨论】:

  • @mysqlnew 在您的列表中,当您运行循环子设置 i=1 时,您有 6、9、3、12,在最后一次迭代中,我的值为 4,而 i=i+1 变为 5,其中 5 在您的列表中不小于或等于 3,因此您将收到错误消息
  • 感谢 Arun 的澄清。对于大样本量,for 循环将是一个问题。
  • @mysqlnew 如果您觉得正确,请投票支持我的回答
  • 对不起。虽然 for 循环消除了错误,但它并没有多大帮助。该列表用于生成 4 个随机数集,它们之间不会被替换。输出应该像我的列表示例一样,但在一行中生成。 3 5 6 1 5 6 9 13 12 7 11 12 14 11 14....感谢您的帮助,但我无法投票给您的答案。 @alistaire answer 消除了警告,但仍然没有在一行中得到输出。感谢大家的帮助。
  • x &lt;- c(); x &lt;- c(x, sample(start:end, replace=T)) 在一行中获取输出。
猜你喜欢
  • 2021-10-30
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多