# [R] error message when using outer function

Petr Klasterecky klaster at karlin.mff.cuni.cz
Mon Mar 5 21:25:36 CET 2007

```Comments inside.

Reinman, Grant napsal(a):
> Dear R-users,
> I have two sets of code that appear to me to be equivalent, shown below, and
> yet I get the error message
>
> "Error in dim(robj) <- c(dX, dY) : dim<- : dims [product 4] do not match the
> length of object [1]"
>
> after executing the assignment to logdens2.  Both functions post.a1 and
> post.a2 return the same values when run alone and not embedded in the
> function outer.  I would appreciate help in understanding the differences
> between these two sets of code.
>
> The code in post.a1 is from Gelman, Carlin, Stern, and Rubin's Bayesian Data
> Analysis solutions, problem 3.5.  I was trying to modify this code in
> post.a2 when I ran into this error.
>
>
> post.a1 <- function(mu,sd,y){
>   ldens <- 0
>   for (i in 1:length(y)) ldens <- ldens + log(dnorm(y[i],mu,sd))
>   ldens}
> y <- c(10,10,12,11,9)
> mugrid <- c(10,11)
> sdgrid <- c(1,1.2)
> logdens1 <- outer (mugrid, sdgrid, post.a1, y)
> #*** no error messages ***

Actually pretty ugly coding (for a textbook) in my opinion... Try what
you get with
y <- c(10,10,12,11,9)
mugrid <- c(10,11)
sdgrid <- c(1,1.2)
log(dnorm(y[1],mean=mugrid,sd=sdgrid))

[1] -0.9189385 -1.4484823
This is in a perfect accordance with help(dnorm), which says you are
allowed to specify a vector of means and SDs. Here 2 values were
specified, so you obtain 2 density values.

Now, adding a vector of length 2 to a constant:
#not run here# ldens <- ldens + log(dnorm(y[i],mu,sd))
is again a vector of length 2.

However, using sum() in your code below gives you just a single number
and R starts complaining because the dimensions don't match.

Petr

>
>
> post.a2 <- function(mu,sd,y)
> {
>   ldens <- sum(log(dnorm(y,mu,sd)))
>   ldens
> }
> y <- c(10,10,12,11,9)
> mugrid <- c(10,11)
> sdgrid <- c(1,1.2)
> logdens2 <- outer (mugrid, sdgrid, post.a2, y)
> #***error message occurs here ***
>
> Thank You!
>
> Grant Reinman
> e-mail:grant.reinman at pw.utc.com
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help