r逐行取n列 [英] r get mean of n columns by row

查看:199
本文介绍了r逐行取n列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的数据框架

I have a simple data.frame

> df <- data.frame(a=c(3,5,7), b=c(5,3,7), c=c(5,6,4))
> df
  a b c
1 3 5 5
2 5 3 6
3 7 7 4

有没有一种简单而有效的方式来获取具有相同数量行的新数据框架,但是具有例如列a和b按行的平均值?如下所示:

Is there a simple and efficient way to get a new data.frame with the same number of rows but with the mean of, for example, column a and b by row? something like this:

  mean.of.a.and.b c
1               4 5
2               4 6
3               7 4


推荐答案

使用<$只有前两列的c $ c> rowMeans()然后 cbind()到第三列。

cbind(mean.of.a.and.b = rowMeans(df[-3]), df[3])
#   mean.of.a.and.b c
# 1               4 5
# 2               4 6
# 3               7 4

注意:在您的原始数据中有任何NA值,您可能需要在 rowMeans()中使用 na.rm = TRUE 。请参阅?rowMeans 了解更多。

Note: If you have any NA values in your original data, you may want to use na.rm = TRUE in rowMeans(). See ?rowMeans for more.

这篇关于r逐行取n列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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