开发者

how to calculate mean from part or a list/matrix/dataframe ? and which data type is fastest to do it?

开发者 https://www.devze.com 2023-01-29 23:12 出处:网络
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 co

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消