Reputation:
I tried to make my function much more conveient to read. So, instead of repeating my code many times, I used lapply
. However, I got different result for the same function. My aim is, if I have a large list, for example, X = (x1, x2,..,x10)
. So instead of writing a long code for 10
elements, I would to write simple code using lapply
. But I got different result.
Here is my code:
x1 <- rnorm(10,4,2)
x2 <- rnorm(10, 3,3)
x <- list(x1,x2)
w <- c(0.5,0.5)
ll_1 <- lapply(1:2, function(i) log(w[[i]] * dnorm(x[[i]],log=F)))
ll_new <- sum(unlist(ll_1))
ll_2 <- sum(log(w[[1]]*dnorm(x1,log=F)+w[[2]]*dnorm(x2,log=F)))
> identical(ll_new ,ll_2)
[1] FALSE
Upvotes: 1
Views: 234
Reputation: 1943
Log of sum is not equal to sum of log (log( a + b ) != log(a) + log(b)
)...
x1 <- rnorm(10,4,2)
x2 <- rnorm(10, 3,3)
x <- list(x1,x2)
w <- c(0.5,0.5)
ll_1 <- lapply(1:2, function(i) log(w[[i]] * dnorm(x[[i]],log=F)))
ll_new <- sum(unlist(ll_1))
ll_2 <- sum(log(w[[1]]*dnorm(x[[1]],log=F))+log(w[[2]]*dnorm(x[[2]],log=F)))
identical(ll_new ,ll_2)
[1] TRUE
Upvotes: 1