gpt4 book ai didi

r - 在 R 中合并每月日期

转载 作者:行者123 更新时间:2023-12-04 02:21:36 26 4
gpt4 key购买 nike

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

最佳答案

尝试格式

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))]

关于r - 在 R 中合并每月日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28505444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com