Skip to content

vectors of matrix as iinput to lapply

3 messages · Alaios, Petr Savicky, Poersching

#
On Sun, Feb 05, 2012 at 06:54:02AM -0800, Alaios wrote:
Hi.

Try the following

  a <- matrix(1:16, nrow=4)
  x <- lapply(apply(a, 1, FUN=list), unlist)
  x

  [[1]]
  [1]  1  5  9 13
  
  [[2]]
  [1]  2  6 10 14
  
  [[3]]
  [1]  3  7 11 15
  
  [[4]]
  [1]  4  8 12 16

Hope this helps.

Petr Savicky.
#
Am 05.02.2012 15:54, schrieb Alaios:
Hi Alex,
I don't know exactly what you mean. A small example would be helpfull. 
But how I understand you, you have different choices:
let x be a matrix
x <- matrix(rnorm(24, 10,5), nrow=6)

you could
1.  cut the matrix in a list of vectors (xi)
xi <- list()
for (i in 1:length(x[,1])) xi[[i]] <- x[i,]
lapply(xi, function(f) f/5)

2. use lapply in a loop
y <- list()
for (i in 1:length(x[,1])) y[[i]] <- lapply(x[i,], function (f) f/5)

3. use lapply in this way
lapply(x[1:length(x[,1]),], function (f) f/5)

or
4. combine the apply with the lapply function
apply(x,1,function(f) {
   lapply(f, function (g) g/5)
})

Hope something like this is what you wanted.
Best wishes, Christian