[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
x<-rnorm(100)
dim(x)<-c(10,10)
#Create index for the first and last column in each block (your n would be
50)
n<-2
mim<-seq(from=1,to=dim(x)[2],by=n)
mox<-seq(from=2,to=dim(x)[2],by=n)
#Bind these values in matrix
mat<-cbind(mim,mox)
#Now run apply over the rows of mat, not over the data matrix
apply(mat,1,function(y){mean(x[,c(y[1]:y[2])])})
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
matrix.
HTH,
Daniel
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