r - 如何在 r 中使用 group_by 通过某些列组合数据帧的行,但同时保留其他列
问题描述
这应该很简单,我只是无法让它工作
我有一个all_emissions_state_total
看起来像这样的数据框:
tribe state scc pollutant emissions unit category eis year fraction
NA WY 707 Methane 546 TON onroad NA 2011 NA
NA WY 707 Methane 38 TON onroad NA 2011 NA
NA WY 3405 Methane 2937 TON onroad NA 2011 NA
NA MT 707 Methane 665 TON onroad NA 2011 NA
NA WY 390 CO2 740 TON onroad NA 2011 NA
NA MT 390 CO2 12 TON onroad NA 2011 NA
NA WY 3405 Methane 329 TON onroad NA 2011 NA
GHYU WY 390 CO2 44 TON point NA 2011 NA
BERS WY 390 CO2 64445 TON point NA 2011 596
SDSH KS 707 Methane 123 TON point NA 2011 3890
SDSH MT 707 Methane 58 TON point NA 2011 112
我希望它看起来像这样:
state scc pollutant emissions unit year
WY 707 Methane 584 TON 2011
MT 707 Methane 723 TON 2011
WY 3405 Methane 3266 TON 2011
WY 390 CO2 65229 TON 2011
MT 390 CO2 12 TON 2011
KS 707 Methane 123 TON 2011
在原始数据帧all_emissions_state_total
, tribe
, state
, scc
, pollutant
, emissions
, category
, eis
, 和fraction
变化。unit
永远是 TON,year
永远是 2011 年。
我希望这些行按具有相同state
、scc
和的行进行分组pollutant
,并且该emissions
列是被分组的那些行的总和。tribe
, category
, eis
, andfraction
没关系,可以去掉,但是unit
andyear
需要留下。
这是我认为可行的:
all_emissions_state <- all_emissions_state_total %>%
group_by( state, scc, pollutant ) %>%
summarise( emissions = sum( emissions ) )
但我对此的输出是一个 1x1 数据帧all_emissions_state
,它具有列emissions
和 1 个值,该值是数据帧中所有排放的总和。
解决方案
Base 中的一个选项
New_df <- do.call(rbind,lapply(split(df, with(df,paste0(state,scc,pollutant))), function(x) x[1,c("state","scc","pollutant","emissions","unit","year")]))
New_df$emissions <- sapply( split(df$emissions, with(df,paste0(state,scc,pollutant))), sum)
row.names(New_df) <- NULL
> New_df
state scc pollutant emissions unit year
1 KS 707 Methane 123 TON 2011
2 MT 390 CO2 12 TON 2011
3 MT 707 Methane 723 TON 2011
4 WY 3405 Methane 3266 TON 2011
5 WY 390 CO2 65229 TON 2011
6 WY 707 Methane 584 TON 2011
推荐阅读
- c# - 如何使用 ASP.NET Core 3.1 MVC 和 EF Core 对唯一字段使用数据验证注释?
- laravel - Vue-Router 仅显示使用 Laravel Blade 的基本路由?
- reactjs - joi 根据另一个字段设置布尔默认值
- javascript - 如何从闪亮的 DT 中的单选按钮(使用 JS 回调制作)访问用户输入,并在一个 DT 中有不同的 JS 元素?
- python - OR-tools CP-SAT 求解器是否支持“反射”方法,例如 x.Min() 和 x.Max()?
- python - 如何替换字符串(python)中的列名?
- java - 如何像其他排序列表一样对 ArrayList 进行排序?
- r - R:获取向量中第一个实例的索引大于变量但对于整个列
- angular - Gitlab autodevops 和 Kubernetes,在 review pod 上添加 angular 的配置文件
- python - 如何在 Python 中实现 IDA* 算法以解决 15-Puzzle 问题?