填充列表的每个元素

时间:2016-06-10 18:11:36

标签: r list loops lapply

我正在尝试使用函数rmultinom填充列表的每个元素:

# probabilities of group membership for 3 observations to be generated
probs = data.frame("grp1"=c(.1, .9, 0), "grp2"=c(.2, .2, .6), "grp3"=c(.3,.1,.6))
n = length(probs)

# generate a categorical variable
cat.var = vector("list", n)   # create vector of lists for each observation's indicators
for (j in 1:n)  cat.var[[j]] = rmultinom(1, 1, probs[j,])

# everything is NULL
cat.var

# yet the below works...
cat.var[[1]] = rmultinom(1, 1, probs[1,])
cat.var[[2]] = rmultinom(1, 1, probs[2,])
cat.var[[3]] = rmultinom(1, 1, probs[3,])

我的问题是:

  1. 上面有什么问题?
  2. 是否有更好的方法来实现所需的结果,例如使用lapply?当我尝试lapply时,我不确定如何让FUN参数对于列表的每个元素都有所不同(即,应为cat.var[[j]]分配由{生成的值{ {1}})。

1 个答案:

答案 0 :(得分:1)

obs中的for(i in 1:obs)更改为for(i in 1:n)并设置seed

# Set seed for reproducibility
set.seed(113)
for (j in 1:n)  cat.var[[j]] = rmultinom(1, 1, probs[j,])

我明白了:

cat.var
    [[1]]
     [,1]
grp1    0
grp2    1
grp3    0

[[2]]
     [,1]
grp1    0
grp2    1
grp3    0

[[3]]
     [,1]
grp1    0
grp2    1
grp3    0

使用lapply编写代码时,我们会创建一个带有x索引的辅助函数来迭代probs

set.seed(113)

lstyle = function(x, n, size, prob){
  rmultinom(n, size, probs[x,])
}

lapply(X = 1:n, FUN = lstyle, n = 1, size = 1, prob = probs)

我们得到:

[[1]]
     [,1]
grp1    0
grp2    1
grp3    0

[[2]]
     [,1]
grp1    0
grp2    1
grp3    0

[[3]]
     [,1]
grp1    0
grp2    1
grp3    0