即使使用set.seed,手动和for循环也会返回不同的值

时间:2017-10-29 07:44:37

标签: r

我试图自动找到这些函数的总和。然后,为了确保它按预期运行,我手动执行并使用for循环,但结果是不同的。这是我的代码(我的函数比这个例子更难,但是类似的)

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]],sd[[2]]),
rnorm(10,mu1[[3]],sd[[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)))

ll <- list()
for(i in 1:3){
 ll[[i]] <-  ta[[i]]*log(w[i])+dnorm(mylist[[i]],log = T)
 sum(ll[[i]])
}

手动和循环分别返回这些结果,

[1] -89.6547
[1] -84.28907

为什么这些结果不平等。请帮助,这仍然是由于set.seed

1 个答案:

答案 0 :(得分:0)

执行顺序中的大括号可能存在​​问题。在第一种情况下,由于运算符优先级,首先发生ta[[3]]*log(w[[3]],然后将输出添加到dnorm(my[[3]], log = TRUE)

sum(ta[[3]]*log(w[3]) + dnorm(mylist[[3]], log = TRUE))
#[1] -84.28907

然而,在下面,我们将ta[[3]]乘以(log(w[3]) + dnrom(mylist[[3]], log = TRUE))的总和,因为它在括号内。

sum(ta[[3]]*(log(w[3]) + dnorm(mylist[[3]], log = TRUE)))
#[1] -33.48956

在第二个中,大括号从(log(w[3]...)

开始

要检查一下,我们正在使用mapply,它会提供输出-89.6547,它是所有三种手动案例的总和。

sum(mapply(function(x, y, z) sum(x*(y +dnorm(z, log = TRUE))), ta, log(w), mylist))
#[1] -89.6547

另外,如果我们更正for循环中的大括号,输出将是相同的

ll <- list()
 for(i in 1:3){
  ll[[i]] <-  sum(ta[[i]]*(log(w[i])+dnorm(mylist[[i]],log = T)))

 }
sum(unlist(ll))
#[1] -89.6547