首页 > 解决方案 > R中的平均(平均值)2列数据框

问题描述

我正在尝试根据他们在列 A 中的名称来平均 2 列(收入和支出),如下所示(以找到每个列的平均年值)。我想我遇到了语法错误,但不确定我哪里出错了,我尝试了一些不同的变体,但没有运气。

这是我的表格片段;

GroupName   Year    Age Size    Income  Expenditure
yellow      2008    35  2.7     46704   42394
red         2008    29  2.6     23404   25270
yellow      2010    40  2.3     16747   21145
red         2012    34  2.8     31308   29855
blue        2008    31  3.0     49106   46561
green       2008    35  2.6     61674   52776

这是我的代码;

NewGroupfactsDS <- NewGroupfactsDS %>%
group_by(GroupName) %>% summarize(AvgExpenditure = mean(Expenditure), summarize(AvgIncome = mean(Income))

提前感谢您的帮助:)

标签: r

解决方案


这里有两种方法,第一种方法across和第二种方法是纠正问题代码中的错误。

library(dplyr)

NewGroupfactsDS <- NewGroupfactsDS %>%
  group_by(GroupName) %>% 
  summarize(across(c(Expenditure, Income), mean))

NewGroupfactsDS <- NewGroupfactsDS %>%
  group_by(GroupName) %>% 
  summarize(AvgExpenditure = mean(Expenditure),
            AvgIncome = mean(Income))

推荐阅读