Dplyr - 表示多列 [英] Dplyr - Mean for multiple columns

查看:141
本文介绍了Dplyr - 表示多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算几列的平均值,创建一个新列,使用dplyr并且不融合+合并。

I want to calculate the mean for several columns, creating a new column, using dplyr and without melting + merging.

> head(growth2)
  CODE_COUNTRY CODE_PLOT IV12_ha_yr IV23_ha_yr IV34_ha_yr IV14_ha_yr IV24_ha_yr IV13_ha_yr
1            1         6       4.10       6.97         NA         NA         NA       4.58
2            1        17       9.88       8.75         NA         NA         NA       8.25
3            1        30         NA         NA         NA         NA         NA         NA
4            1        37      15.43      15.07      11.89      10.00      12.09      14.33
5            1        41      20.21      15.01      14.72      11.31      13.27      17.09
6            1        46      12.64      14.36      13.65       9.07      12.47      12.36
> 

我需要数据集中的新列,其中包含所有IV列的平均值。
我尝试过:

I need a new column within the dataset with the mean of all the IV columns. I tried this:

growth2 %>% 
  group_by(CODE_COUNTRY, CODE_PLOT) %>%
  summarise(IVmean=mean(IV12_ha_yr:IV13_ha_yr, na.rm=TRUE))

并根据使用的示例返回了几个错误,例如:

And returned several errors depending on the example used, such as:

Error in NA_real_:NA_real_ : NA/NaN argument

Error in if (trim > 0 && n) { : missing value where TRUE/FALSE needed


推荐答案

您不需要分组,只需 select()然后 mutate()

$ b

You don't need to group, just select() and then mutate()

library(dplyr)
mutate(df, IVMean = rowMeans(select(df, starts_with("IV")), na.rm = TRUE))

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

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