r - 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))
提前感谢您的帮助:)
解决方案
这里有两种方法,第一种方法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))
推荐阅读
- python - 有什么方法可以调整 DAG 应该有多“胖”和多“高”?
- c++ - 返回完整或空 std::optional 时的 if-then-else 与三元运算符
- visual-studio-code - 当另一个调试会话关闭时关闭一个调试会话
- android - 如何使用电子邮件和密码生成 Youtube 的 API Key
- r - 如果索引从 1 开始,为什么矩阵允许索引为零?
- c++ - 多项式不可约性的错误评估
- reactjs - 在 JSON 位置 0 中展示意外令牌?
- java - 向发件人无法接收的一组用户发送消息
- html - 使用 React Link 或标签 href 进行 JSX 格式化?
- javascript - check_ajax_referer 返回 -1