我有一个看起来像这样的数据框:
year <- year
month <- c(1,1,1,1,1,2,2,2,3,3)
county <- c("Upshur", "Upshur", "Upshur", "Collin","Collin","Upshur","Upshur", "Collin","Upshur","Collin")
citation <- c(1,0,1,1,1,0,1,0,1,1)
df <- data.frame(year, month, county, citation)
# year month county citation
#1 2007 1 Upshur 1
#2 2007 1 Upshur 0
#3 2007 1 Upshur 1
#4 2007 1 Collin 1
#5 2007 1 Collin 1
#6 2007 2 Upshur 0
#7 2007 2 Upshur 1
#8 2007 2 Collin 0
#9 2007 3 Upshur 1
#102007 3 Collin 1
#...
在我有个别警察停靠站的事件中,根据引用是1还是0来说明停靠站是被引用还是被终止。我的目标是将这个数据整合到一个较小的数据框中,在该数据框中,票的发生频率和列出每个月每个县的引用。基本上,看起来像这样:
# year month county citations_given warnings_given
2007 1 Upshur 2 1
2007 1 Collin 2 0
2007 2 Upshur 1 0
2007 2 Collin 0 1
2007 3 Upshur 1 0
2007 3 Collin 1 0
...
任何建议将不胜感激!
答案 0 :(得分:1)
我为此推荐from pptx.chart.data import CategoryChartData
# ---define new chart data---
chart_data = CategoryChartData()
chart_data.categories = ['East', 'West', 'Midwest']
chart_data.add_series('Series 1', (19.2, 21.4, 16.7))
# ---replace chart data---
chart.replace_data(chart_data)
软件包。
dplyr
答案 1 :(得分:1)
我强烈建议使用data.table包。
library(data.table)
setDT(df)
df[,list(warn_given = sum(citation==0),cite_given = sum(citation)),
by=c('year', 'month', 'county')]
答案 2 :(得分:0)
使用基本包并清除列名,在aggregate
调用中考虑一个多功能:
agg_df <- setNames(do.call(data.frame,
aggregate(citation ~ year + month + county, df, function(x)
c(citations_given = sum(x),
warnings_given = sum(x==0))
)
), c("year", "month", "county", "citations_given", "warnings_given")
)
agg_df
# year month county citations_given warnings_given
# 1 2007 1 Collin 2 0
# 2 2007 2 Collin 0 1
# 3 2007 3 Collin 1 0
# 4 2007 1 Upshur 2 1
# 5 2007 2 Upshur 1 1
# 6 2007 3 Upshur 1 0