2012-09-20 33 views
16

我有一个函数,它包含一个循环遍历两个列表并构建一些计算的数据。我想返回这些数据作为一个列表的列表,索引的一些价值,但我得到的任务是错误的。在R中建立一个循环列表 - 获取正确的项目名称

的我想要做的,我要去哪里错了会是一个小例子:

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,你会发现有些事情是每个项目的命名方式都会出现错误。

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

谢谢

ps。我知道在R里面有其中一个出现故障如果一个人有诉诸循环感,但在这种情况下,我觉得有道理;-)

+4

'c'不是命名对象的好东西! – BenBarnes

+0

确实......点了! Thx – Hassantm

回答

31

它的工作原理,如果你不使用append命令:

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 
+1

ahhh ...打我3秒! – seancarmody

+0

接近... –

+0

抱歉,我错过了那一个!谢谢你们! – Hassantm

4

变化

mybiglist[[name]] <- append(mybiglist, tmp) 

mybiglist[[name]] <- tmp 
+1

谢谢肖恩......那就是诀窍! – Hassantm

1

为了表明一个expli CIT for循环不需要

unif_norm <- replicate(5, list(uniform = runif(10), 
    normal = rnorm(16)), simplify=F) 

binomials <- lapply(seq_len(5)/10, function(prob) { 
list(binomial = rbinom(n = 5 ,size = 8, prob = prob))}) 

biglist <- setNames(mapply(c, unif_norm, binomials, SIMPLIFY = F), 
        paste0('item:',seq_along(unif_norm))) 

一般来说,如果你走了for环路最好是事先预先指定的名单。这是更高效的内存。

mybiglist <- vector('list', 5) 
names(mybiglist) <- paste0('item:', seq_along(mybiglist)) 
for(i in seq_along(mybiglist)){ 
    a <- runif(10) 
    b <- rnorm(16) 
    c <- rbinom(8, 5, i/10) 

    tmp <- list(uniform=a, normal=b, binomial=c) 
    mybiglist[[i]] <- tmp 
} 
+0

谢谢......虽然我不想实际创建统一,正常和二项分布的列表;-)这是我之后的命名约定。 – Hassantm

+0

至少记得预先分配! – mnel