我正在尝试使用函数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,])
我的问题是:
lapply
?当我尝试lapply
时,我不确定如何让FUN
参数对于列表的每个元素都有所不同(即,应为cat.var[[j]]
分配由{生成的值{ {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