[R] run function on subsets of matrix
fisken
torpedofisken at gmail.com
Sun Mar 27 04:26:54 CEST 2011
I was wondering if it is possible to do the following in a smarter way.
I want get the mean value across the columns of a matrix, but I want
to do this on subrows of the matrix, given by some vector(same length
as the the number of rows). Something like
nObs<- 6
nDim <- 4
m <- matrix(rnorm(nObs*nDim),ncol=nDim)
fac<-sample(1:(nObs/2),nObs,rep=T)
##loop trough different 'factor' levels
for (i in unique(fac))
print(apply(m[fac==i,],2,mean))
Now, the problem is that if a value in 'fac' only occurs once, the
'apply' function will complain.
But I think, this can also be written more cleverly using some R style
construct using factorlevels.
Thanks
More information about the R-help
mailing list