[R] A question on operation on list

Tony Plate tplate at acm.org
Wed Jul 22 21:39:59 CEST 2009


Here's one way:

> set.seed(1)
> x1 <- lapply(1:5, function(i) rnorm(2))
> x2 <- lapply(x1, function(x) outer(x, x))
> Reduce("+", x2, 0)
          [,1]      [,2]
[1,]  1.768406 -1.534413
[2,] -1.534413  3.890200
> 

and another way using the abind package:

> library(abind)
> dim(abind(along=0, x2))
[1] 5 2 2
> colSums(abind(along=0, x2))
          [,1]      [,2]
[1,]  1.768406 -1.534413
[2,] -1.534413  3.890200
> 

-- Tony Plate

megh wrote:
> Hi,
> I have created a list object like that :
> x = vector("list")
> for (i in 1:5) x[[i]] = rnorm(2) 
> x
> 
> Now I want to do two things :
> 1. for each i, I want to do following matrix calculation : t(x[[i]]) %*%
> x[[i]] i.e. for each i, I want to get a 2x2 matrix
> 2. Next I want to get  x[[1]] + x[[2]] +....
> 
> I did following : res=vector("list"); res = sapply(x, function(i) t(x[[i]])
> %*% x[[i]])
> However above syntax is not giving desired result. Any suggestion please?
>




More information about the R-help mailing list