Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
生成多个列表以保存for循环中的数据_R_List_For Loop - Fatal编程技术网

生成多个列表以保存for循环中的数据

生成多个列表以保存for循环中的数据,r,list,for-loop,R,List,For Loop,我将每个棒球队的得分和允许得分数据存储在列表中;以下是3个团队的数据: > str(d) List of 3 $ : num [1:32, 1:2] 2 2 3 4 6 3 2 14 5 0 ... ..- attr(*, "dimnames")=List of 2 .. ..$ : NULL .. ..$ : chr [1:2] "R" "RA" ..- attr(*, "na.action")=Class 'omit' num [1:134] 33 34 35 36

我将每个棒球队的得分和允许得分数据存储在列表中;以下是3个团队的数据:

> str(d)
List of 3
 $ : num [1:32, 1:2] 2 2 3 4 6 3 2 14 5 0 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : NULL
  .. ..$ : chr [1:2] "R" "RA"
  ..- attr(*, "na.action")=Class 'omit'  num [1:134] 33 34 35 36 37 38 39 40 41 42 ...
 $ : num [1:33, 1:2] 0 3 3 2 0 8 6 7 4 6 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : NULL
  .. ..$ : chr [1:2] "R" "RA"
  ..- attr(*, "na.action")=Class 'omit'  num [1:133] 34 35 36 37 38 39 40 41 42 43 ...
 $ : num [1:35, 1:2] 1 0 7 2 6 1 5 7 0 3 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : NULL
  .. ..$ : chr [1:2] "R" "RA"
  ..- attr(*, "na.action")=Class 'omit'  num [1:131] 36 37 38 39 40 41 42 43 44 45 ...
我正在运行一个模拟,在那里我对每个团队的得分进行采样,并将其与允许的得分进行比较。然后我将结果存储在一个列表中。下面是for循环:

z <- list()
for(i in 1:length(d)){
  s <- sample(d[[i]][, 1], length(d[[i]][, 1]), replace = TRUE)
  while(any(ind <- s == d[[i]][, 2])) 
    s[ind] <- sample(d[[i]][, 1], sum(ind), replace = TRUE)
  wins <- sum(s > d[[i]][, 2])
  losses <- length(d[[i]][, 1]) - wins
  win_perc <- wins/length(d[[i]][, 1])

  z[[i]] <- c(wins, losses, win_perc)
}

我需要使用复制功能吗?

1)如果要在列表上循环,应该使用
lappy
,这将比
for
循环更有效。循环会增长对象,这是可以执行的最慢的操作之一。2) 你似乎有一个矩阵列表。我认为,如果您将数据重组为一个data.table,您可以编写效率更高的代码。输出也应该是data.table。3) 和往常一样,如果您提供了可复制的数据,例如,
dput(d)
,那么回答这个问题会更容易。口头描述一下你的模拟也很好。我会接受你的建议,用data.table试试
> z
[[1]]
[1] 16.0 16.0  0.5

[[2]]
[1] 13.0000000 20.0000000  0.3939394

[[3]]
[1] 21.0 14.0  0.6