An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20120205/e02b6798/attachment.pl>
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:
Dear all I am using lapply (actually mclapply that share the same syntax). I want to call the same function that takes as input a vector. My initial data structure is a matrix that I want to cut it to multiple vectors (one vector for every row of the matrix) and then feed that to the function by using mclapply. Could you please help me converting the matrices to nrow times vectors.
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:
Dear all I am using lapply (actually mclapply that share the same syntax). I want to call the same function that takes as input a vector. My initial data structure is a matrix that I want to cut it to multiple vectors (one vector for every row of the matrix) and then feed that to the function by using mclapply. Could you please help me converting the matrices to nrow times vectors. I would like to thank you in advance for your help Regards Alex
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