我有一個資料框,列出了 1991 年至 2020 年間每個州的個別大規模槍擊事件。我想 1)總結每個州每年的受害者總數,以及 2)總結每個州每年發生的大規模槍擊事件的總數。
到目前為止,我只設法獲得了 1991 年至 2020 年間每個州的受害者總數。而且我什至不確定如何獲得每個州每年發生的事件總數的列。我可以對該aggregate
功能進行任何調整,還是有其他功能可以獲取我想要的資訊?
我有的:
combined = read.csv('https://raw.githubusercontent.com/bandcar/massShootings/main/combo1991_2020_states.csv')
> head(combined)
state date year fatalities injured total_victims
3342 Alabama 04/07/2009 2009 4 0 4
3351 Alabama 03/10/2009 2009 10 6 16
3285 Alabama 01/29/2012 2012 5 0 5
135 Alabama 12/28/2013 2013 3 5 8
267 Alabama 07/06/2013 2013 0 4 4
557 Alabama 06/08/2014 2014 1 4 5
q = aggregate(total_victims ~ state,data=combined,FUN=sum)
> head(q)
state total_victims
1 Alabama 364
2 Alaska 19
3 Arizona 223
4 Arkansas 205
5 California 1816
6 Colorado 315
我對每個州每年想要的東西:
year state total_victims total_shootings
1 2009 Alabama 20 2
2 2012 Alabama 5 1
3 2013 Alabama 12 2
4 2014 Alabama 5 1
uj5u.com熱心網友回復:
您可以與tidyverse 軟體包group_by
結合使用。summarise()
library(tidyverse)
combined |>
group_by(state, year) |>
summarise(total_victims = sum(total_victims),
total_shootings = n())
這是你得到的結果:
# A tibble: 457 x 4
# Groups: state [52]
state year total_victims total_shootings
<chr> <int> <int> <int>
1 Alabama 2009 20 2
2 Alabama 2012 5 1
3 Alabama 2013 12 2
4 Alabama 2014 10 2
5 Alabama 2015 17 4
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/515278.html
標籤:r数据框多列计算列