[英]average (mean) 2 columns of dataframe in R
我正在嘗試根據他們在列 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))
只需刪除第二個summarize
。 並考慮 Rui Barradas across
建議
NewGroupfactsDS <- NewGroupfactsDS %>%
group_by(GroupName) %>%
summarize(AvgExpenditure = mean(Expenditure), AvgIncome = mean(Income))
Output:
GroupName AvgExpenditure AvgIncome
<chr> <dbl> <dbl>
1 blue 46561 49106
2 green 52776 61674
3 red 27562. 27356
4 yellow 31770. 31726.
基地 R 答案
aggregate(DF[,4:5], list("GroupName" = DF$GroupName), mean)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.