在R中的循环中建立清单-取得正确的项目名称 [英] Building a list in a loop in R - getting item names correct

查看:150
本文介绍了在R中的循环中建立清单-取得正确的项目名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,其中包含一个遍历两个列表的循环并建立一些计算出的数据.我想以列表列表的形式返回这些数据,并以一些值索引,但是我分配的错误.

I have a function which contains a loop over two lists and builds up some calculated data. I would like to return these data as a lists of lists, indexed by some value, but I'm getting the assignment wrong.

关于我正在尝试做的事情以及我要去哪里的错误的一个最小示例是:

A minimal example of what I'm trying to do, and where i'm going wrong would be:

mybiglist <- list()
for(i in 1:5){
    a <- runif(10)
    b <- rnorm(16)
    c <- rbinom(8, 5, i/10)
    name <- paste('item:',i,sep='')
    tmp <- list(uniform=a, normal=b, binomial=c)
    mybiglist[[name]] <- append(mybiglist, tmp)
}

如果运行此命令并查看输出的mybiglist,您会发现每个项目的命名方式都出了问题.

If you run this and look at the output mybiglist, you will see that something is going very wrong in the way each item is being named.

关于我将如何实现我真正想要的东西的任何想法?

Any ideas on how I might achieve what I actually want?

谢谢

ps.我知道在R中,如果必须诉诸循环,就会有失败的感觉,但是在这种情况下,我确实感到有道理;-)

ps. I know that in R there is a sense in which one has failed if one has to resort to loops, but in this case I do feel justified ;-)

推荐答案

如果不使用append命令,它将起作用:

It works if you don't use the append command:

mybiglist <- list()
for(i in 1:5){
  a <- runif(10)
  b <- rnorm(16)
  c <- rbinom(8, 5, i/10)
  name <- paste('item:',i,sep='')
  tmp <- list(uniform=a, normal=b, binomial=c)
  mybiglist[[name]] <- tmp
}

# List of 5
# $ item:1:List of 3
# ..$ uniform : num [1:10] 0.737 0.987 0.577 0.814 0.452 ...
# ..$ normal  : num [1:16] -0.403 -0.104 2.147 0.32 1.713 ...
# ..$ binomial: num [1:8] 0 0 0 0 1 0 0 1
# $ item:2:List of 3
# ..$ uniform : num [1:10] 0.61 0.62 0.49 0.217 0.862 ...
# ..$ normal  : num [1:16] 0.945 -0.154 -0.5 -0.729 -0.547 ...
# ..$ binomial: num [1:8] 1 2 2 0 2 1 0 2
# $ item:3:List of 3
# ..$ uniform : num [1:10] 0.66 0.094 0.432 0.634 0.949 ...
# ..$ normal  : num [1:16] -0.607 0.274 -1.455 0.828 -0.73 ...
# ..$ binomial: num [1:8] 2 2 3 1 1 1 2 0
# $ item:4:List of 3
# ..$ uniform : num [1:10] 0.455 0.442 0.149 0.745 0.24 ...
# ..$ normal  : num [1:16] 0.0994 -0.5332 -0.8131 -1.1847 -0.8032 ...
# ..$ binomial: num [1:8] 2 3 1 1 2 2 2 1
# $ item:5:List of 3
# ..$ uniform : num [1:10] 0.816 0.279 0.583 0.179 0.321 ...
# ..$ normal  : num [1:16] -0.036 1.137 0.178 0.29 1.266 ...
# ..$ binomial: num [1:8] 3 4 3 4 4 2 2 3

这篇关于在R中的循环中建立清单-取得正确的项目名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆