按因子计算组的均值 [英] compute means of a group by factor

查看:36
本文介绍了按因子计算组的均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法可以改进或者更简单地做到这一点?

Is there a way that this can be improved, or done more simply?

means.by<-function(data,INDEX){
  b<-by(data,INDEX,function(d)apply(d,2,mean))
  return(structure(
    t(matrix(unlist(b),nrow=length(b[[1]]))),
      dimnames=list(names(b),col.names=names(b[[1]]))
  ))
}

这个想法与 SAS MEANS BY 语句相同.函数 'means.by' 接受一个 data.frame 和一个索引变量,并为对应于 INDEX 的唯一值的每组行计算 data.frame 列的平均值,并返回一个带有行的新数据框命名 INDEX 的唯一值.

The idea is the same as a SAS MEANS BY statement. The function 'means.by' takes a data.frame and an indexing variable and computes the mean over the columns of the data.frame for each set of rows corresponding to the unique values of INDEX and returns a new data frame with with the row names the unique values of INDEX.

我确信在 R 中一定有更好的方法来做到这一点,但我想不出任何事情.

I'm sure there must be a better way to do this in R but I couldn't think of anything.

推荐答案

聚合函数是否满足您的需求?

Does the aggregate function do what you want?

如果没有,请查看 plyr 包,它提供了几个选项,可以将事物拆开,对碎片进行计算,然后再将其重新组合在一起.

If not, look at the plyr package, it gives several options for taking things apart, doing computations on the pieces, then putting it back together again.

您也可以使用 reshape 包执行此操作.

You may also be able to do this using the reshape package.

这篇关于按因子计算组的均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆