how to calculate mean from part or a list/matrix/dataframe ? and which data type is fastest to do it?
I have this matrix (may it be other similar data type) with two columns x and y and I want for each x calculate t开发者_Python百科he mean of all values from y corresponding to this particular x (Of course when there are more than one x with particular value).
Use ave
or aggregate
, depending on how you want the output.
A matrix
will be faster than a data.frame
, but you can only use a matrix
if x
and y
are the same type.
set.seed(21)
x <- cbind(rnorm(20), sample(1:2,20,TRUE))
ave(x[,1], x[,2])
aggregate(x[,1], by=list(x[,2]), FUN=mean)
精彩评论