如何计算数据框中的行均值? [英] how to calculate row means in a data frame?

查看:70
本文介绍了如何计算数据框中的行均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含1000列和8行的数据框,我需要计算行均值.我尝试了以下循环:

I have a dataframe with 1000 columns and 8 rows, I need to calculate row means.I tried this loop:

final <- as.data.frame(matrix(nrow=8,ncol=1))
for(j in 1:8){
  value<- mean(dataframe[j,])
  final[j,]<-value
}

但出现以下错误:

在mean.default(df2 [j,])中:参数不是数字或逻辑:返回NA

In mean.default(df2[j, ]) : argument is not numeric or logical: returning NA

推荐答案

使用 rowMeans()函数:

final$mean <- rowMeans(final, na.rm=TRUE)

请注意,您应避免在日常的 R 操作中使用循环.如果要自己遍历所有行,则可以使用 apply()函数,如下所示:

Note that you should avoid using loops for your everyday R operations. If you want to iterate over all rows yourself, you can use the apply() function like this:

final$mean <- apply(final, 1, function(x) { mean(x, na.rm=TRUE) })

这篇关于如何计算数据框中的行均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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