R中的colsum条件?

时间:2018-04-03 19:23:14

标签: r time-series rowsum

我有这些数据按周拆分,并希望将其更改为每月和/或季度数据。我是否可以使用根据日期或周数对列数据求和的条件?鉴于我有1962年至2016年的数据并且不想将所有周数合并,我不确定如何根据几周来做到这一点。以下是我的数据框设置方式,非常感谢任何建议。

enter image description here

好的,所以按周过滤,我有52或53周的年数。建议的解决方案似乎确实解决了这些问题,即使有些日期是结束日期,有些日期是去年的一些日期。如果我可以按年份和月份创建新列,并在第7-13列(按列而不是行)中汇总列值

enter image description here

2 个答案:

答案 0 :(得分:1)

library(dplyr)
# First create new variable for just the month and year
df$Month_Yr <- format(as.Date(df$Date), "%Y-%m")
# Then group by (dplyr) the months and sum over intended variable
df %>% group_by(Month_Yr) %>% summarise(sum_pideaths = sum(pideaths, na.rm = TRUE))

注意:这只会对列pideaths求和。如果要对所有列求和,请先选择数字列,然后使用summarise_all()

df %>% select(Month_Yr,**numeric_cols**) %>% group_by(Month_Yr) %>% summarise_all(funs(sum = sum(na.rm = TRUE)))

答案 1 :(得分:0)

as.POSIXlt函数提供了一个列表,可以提取该列表以提供类似于C的数字月份值,因为它们从1开始为0。这应该不是分裂的问题。有关选项,请参阅“详细信息”部分,但我可以告诉您没有季度选项。

以下是交付周的代码:

 as.POSIXlt( Sys.Date()+1:60 )$yday %/% 7
 [1] 13 13 13 13 13 14 14 14 14 14 14 14 15 15 15 15 15 15 15 16 16 16 16 16 16 16 17 17 17 17
[31] 17 17 17 18 18 18 18 18 18 18 19 19 19 19 19 19 19 20 20 20 20 20 20 20 21 21 21 21 21 21

但请注意,这不一定与您选择的周开始时一致。您可能需要减去一年中第一年的数字工作日才能使其正确对齐。 (星期日是0个工作日。)

as.POSIXlt( Sys.Date()+1:60 - as.POSIXlt( as.Date( paste0( format(Sys.Date(), "%Y"),"-01-01")))$wday )$yday %/% 7
 [1] 13 13 13 13 13 13 14 14 14 14 14 14 14 15 15 15 15 15 15 15 16 16 16 16 16 16 16 17 17 17
[31] 17 17 17 17 18 18 18 18 18 18 18 19 19 19 19 19 19 19 20 20 20 20 20 20 20 21 21 21 21 21

提供可打印标签的另一个选项zoo::as.yearmon

as.POSIXlt( Sys.Date()+1:60 )$mon
 [1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
[46] 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5


zoo::as.yearmon( Sys.Date()+1:60 )
 [1] "Apr 2018" "Apr 2018" "Apr 2018" "Apr 2018" "Apr 2018" "Apr 2018" "Apr 2018" "Apr 2018"
 [9] "Apr 2018" "Apr 2018" "Apr 2018" "Apr 2018" "Apr 2018" "Apr 2018" "Apr 2018" "Apr 2018"
[17] "Apr 2018" "Apr 2018" "Apr 2018" "Apr 2018" "Apr 2018" "Apr 2018" "Apr 2018" "Apr 2018"
[25] "Apr 2018" "Apr 2018" "Apr 2018" "May 2018" "May 2018" "May 2018" "May 2018" "May 2018"
[33] "May 2018" "May 2018" "May 2018" "May 2018" "May 2018" "May 2018" "May 2018" "May 2018"
[41] "May 2018" "May 2018" "May 2018" "May 2018" "May 2018" "May 2018" "May 2018" "May 2018"
[49] "May 2018" "May 2018" "May 2018" "May 2018" "May 2018" "May 2018" "May 2018" "May 2018"
[57] "May 2018" "May 2018" "Jun 2018" "Jun 2018"

zoo包还有一个as.yearqtr函数:

 zoo::as.yearqtr( Sys.Date()+seq(0, 180, by=30) )
#[1] "2018 Q2" "2018 Q2" "2018 Q2" "2018 Q3" "2018 Q3" "2018 Q3" "2018 Q3"

“引擎盖下”(或“引擎盖”视情况而定)此功能实际上也提供了数值,但是具有特殊打印方法的类:

 unclass( zoo::as.yearqtr( Sys.Date()+seq(0, 180, by=30) ) )
[1] 2018.25 2018.25 2018.25 2018.50 2018.50 2018.50 2018.50