I have the following code that I am trying to execute using the whole object approach and get rid of the for loop. I have looked at the manual and seached the database for examples or similar questions with no luck. The following example works without any problems. for (j in 1:186) { entropy.cogp[1:30000, j]<-alpha3[1:30000]*c[j,2] } But when I try to remove the for loop and use entropy.cogp[1:30000, 1:186]<-alpha3[1:30000]*c[1:186,2] R tries to multiply the first member of alpha3 with the first member of c[,2] and once c is exhausted, it multiplies the 187th member of alpha3 with the first member of c[,2] and so on, resulting in an error where it requires the size of alpha3 to be an exact multiple of the size of c. This is clearly not what is intended by the for loop given above. Is there a way to do this using a whole object approach to make things run faster? Or is the for loop the only way of doing this? Thanks...
you are looking for the outer product ?outer> a <- 1:6 > cc <- matrix(1:6, 3, 2)> e <- matrix(0, 6,3) > for (j in 1:3) e[,j] <- a*cc[j,2] > e[,1] [,2] [,3] [1,] 4 5 6 [2,] 8 10 12 [3,] 12 15 18 [4,] 16 20 24 [5,] 20 25 30 [6,] 24 30 36> a %o% cc[,2][,1] [,2] [,3] [1,] 4 5 6 [2,] 8 10 12 [3,] 12 15 18 [4,] 16 20 24 [5,] 20 25 30 [6,] 24 30 36> >