[R] apply (or similar preferred) for multiple columns

Daniel Malter daniel at umd.edu
Tue Jul 12 22:50:41 CEST 2011

Probably not the most elegant, but a workable solution. Assume you have a
matrix x of dimensions 10 x 10. Assume further you want to calculate the
mean for each successive block of two columns. One way to do this is to
create a matrix that indicates the column numbers from/to which to apply the
function. Example:

#Random matrix

#Create index for the first and last column in each block (your n would be


#Bind these values in matrix

#Now run apply over the rows of mat, not over the data matrix

So you would replace mean(...) with whatever function you want to apply. The
argument to the function must be x[,c(y[1]:y[2])], where x is your data


Dimitris.Kapetanakis wrote:
> Dear all, 
> I would like to use the apply or a similar function belonging to this
> family, but applying for each column (or row) but let say for each q
> columns. For example I would like to apply a function FUN for the first q
> columns of matrix X then for q+1:2*q and so on. If I do apply (X, 2, FUN)
> it applies for each column and not for every q columns. Is that possible
> with any similar function?
> Thank you
> Dimitris

View this message in context: http://r.789695.n4.nabble.com/apply-or-similar-preferred-for-multiple-columns-tp3661835p3663499.html
Sent from the R help mailing list archive at Nabble.com.

More information about the R-help mailing list