R中的平均(平均值)2列数据帧

我正在尝试根据他们在 col 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))

提前感谢您的任何帮助:)

回答

这里有两种方法,第一种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))


以上是R中的平均(平均值)2列数据帧的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>