假设我有一个列表,并希望按顺序选择列表元素(一个接一个)并将其插入函数中。这是我的代码,我手动插入每个元素。如何在不使用apply
函数或for
循环的情况下自动执行此操作。也就是说,如何选择[[1]]
然后[[2]]
。
mu1 <- list(2,3,4)
sd1 <- list(0.5,0.6,0.7)
w <- c(0.5,0.2,0.3)
set.seed(123)
mylist <- list(rnorm(10,mu1[[1]],sd1[[1]]),
rnorm(10,mu1[[2]],sd1[[2]]),
rnorm(10,mu1[[3]],sd1[[3]]))
ta <- list(c(0.5,0.6,0.7,0.4,0.3,0.5,0.65,0.2,0.9,0.1),c(0.4,0.6,0.7,0.2,0.3,0.5,0.65,0.2,0.8,0.3),
c(0.3,0.2,0.7,0.4,0.3,0.5,0.25,0.2,0.6,0.4))
xx <- sum(ta[[1]]*(log(w[1])+dnorm(mylist[[1]],log=T)),ta[[2]]*(log(w[2])+dnorm(mylist[[2]],log = T)),ta[[3]]*
(log(w[3])+dnorm(mylist[[3]],log = T)))
答案 0 :(得分:2)
我们可以使用for
循环
lst <- vector('list', length(ta))
for(i in seq_along(ta)) {
lst[[i]] <- sum(ta[[i]]*(log(w[i])+dnorm(mylist[[i]],log=TRUE)))
}
xx1 <- sum(unlist(lst))
identical(xx, xx1)
#[1] TRUE
或者这可以通过将'ta'和'mylist'转换为matrix
xx2 <- sum(do.call(rbind, ta)*(log(w)+ dnorm(do.call(rbind, mylist), log = TRUE)))
identical(xx, xx2)
#[1] TRUE
答案 1 :(得分:2)
使用* apply函数,尤其是mapply
,您可以执行以下操作。
yy <- sum(mapply(function(x, y, z) x * (log(y)+dnorm(z,log=T)), ta, w, mylist))
yy
[1] -89.6547
检查它们是否相同。
identical(yy, xx)
[1] TRUE