R是否有将日期合并为几个月的功能?
dates <- c(20130401, 20130403, 20130504, 20130508, 20130511,
20130716, 20130719, 20130723, 20130729, 20130907)
cost <- c(12, 41, 89, 45.5, 32.89, 74, 76, 12, 15.78, 10)
data <- data.frame(dates,cost)
data$dates <- as.Date(as.character(data$dates), "%Y%m%d")
基本上,我正在寻找与此类似的输出。当我必须合并/堆栈时,我必须摆脱日期之后的几天?所以,格式化yyyy-mm。
dates total_cost_per_month
2013-04 53
2013-05 167.39
2013-07 177.78
2013-09 10
答案 0 :(得分:3)
尝试format
aggregate(cbind(total_cost_per_month=cost)~cbind(dates=format(dates,
'%Y-%m')), data, sum)
# dates total_cost_per_month
#1 2013-04 53.00
#2 2013-05 167.39
#3 2013-07 177.78
#4 2013-09 10.00
或者您可以使用sub
library(data.table)
setDT(data)[, list(total_cost_per_month= sum(cost)),
list(dates=sub('-..$', '', dates))]