[R] applying function to multiple columns of a matrix

Federico Calboli f.calboli at imperial.ac.uk
Tue Jul 12 15:07:10 CEST 2011


Hi,

I want to apply a function to a matrix, taking the columns 3 by 3. I could use a for loop:

for(i in 1:3){ # here I assume my data matrix has 9 columns
j = i*3
set = my.data[,c(j-2,j-1,j)]
my.function(set)
}

which looks cumbersome and possibly slow. I was hoping there is some function in the apply()/lapply() families that could take 3 columns at a time. 

I though of turning mydata in a list, then using lapply()

new.data = list(my.data[,1:3], my.data[,4:6], my.data[,7:9])
lapply(new.data, my.function)

but that might incur in too much memory penalty and does have the issue of requiring a for loop to create the list (not all my data is conveniently of 9 columns only).

Any suggestion would be much appreciated.

Bw

Federico


--
Federico C. F. Calboli
Department of Epidemiology and Biostatistics
Imperial College, St. Mary's Campus
Norfolk Place, London W2 1PG

Tel +44 (0)20 75941602   Fax +44 (0)20 75943193

f.calboli [.a.t] imperial.ac.uk
f.calboli [.a.t] gmail.com



More information about the R-help mailing list