我目前正在使用R编程语言编写脚本,但我遇到了麻烦。
我的时间序列数据的组织方式是每月30天,1年12个月。但是,我需要在一年中适当的365天组织数据,如一个月中的30天,一个月中的31天等。
R是否有一种简单的方法可以识别一个月内有30天并且在该参数范围内操作?目前,我的脚本在UNIX时间内从源代码转换天数,并且它会计数。
例如:
startingdate <- "20060101"
endingdate <- "20121230"
date <- seq(from = as.Date(startingdate, "%Y%m%d"), to = as.Date(endingdate, "%Y%m%d"), by = "days")
这会产生一系列日期,每个月有29天/ 30天/ 31天等。但是,我的数据目前每月组织30天,无论是29天还是31天。
感谢。
答案 0 :(得分:4)
前4个解决方案基本上是使用expand.grid
的同一主题的变体。 (3)使用magrittr而其他人不使用包裹。最后两个工作是通过创建长序列数,然后挑选出具有月和日范围的数字。
1)申请这会给出一系列yyyymmdd数字,每个月有30天。请注意,在这种情况下定义yrs
的行与yrs <- 2006:2012
相同,因此如果年份很方便,我们可以缩短该行。如果您想要输入字符串输出,请在定义as.numeric
的行中省略s
。另外,s
和d
是相同的,因为我们有整整一年的时间,所以我们可以省略定义d
的行,并在这种情况下使用s
作为答案如果我们总是处理整年。
startingdate <- "20060101"
endingdate <- "20121230"
yrs <- seq(as.numeric(substr(startingdate, 1, 4)), as.numeric(substr(endingdate, 1, 4)))
g <- expand.grid(yrs, sprintf("%02d", 1:12), sprintf("%02d", 1:30))
s <- sort(as.numeric(apply(g, 1, paste, collapse = "")))
d <- s[ s >= startingdate & s <= endingdate ] # optional if whole years
运行一些检查。
head(d)
## [1] 20060101 20060102 20060103 20060104 20060105 20060106
tail(d)
## 20121225 20121226 20121227 20121228 20121229 20121230
length(d) == length(2006:2012) * 12 * 30
## [1] TRUE
2)不适用另一种变体就是这样。在此和以下解决方案中,我们使用{1}中计算的yrs
,因此我们省略它以避免冗余。此外,在此解决方案和以下解决方案中,同样省略了一个设置d
的相应行,以避免冗余 - 如果您没有整年,则添加定义{{1}的行在(1)用d
替换该行中的s
。
s2
3)magrittr 这也可以使用magrittr这样编写:
g2 <- expand.grid(yr = yrs, mon = sprintf("%02d", 1:12), day = sprintf("%02d", 1:30))
s2 <- with(g2, sort(as.numeric(paste0(yr, mon, day))))
4)do.call 另一种变体。
library(magrittr)
expand.grid(yr = yrs, mon = sprintf("%02d", 1:12), day = sprintf("%02d", 1:30)) %>%
with(paste0(yr, mon, day)) %>%
as.numeric %>%
sort -> s3
5)子集序列从开始日期到结束日期创建一系列数字,如果每个数字的形式为yyyymmdd,则选择mm和dd在范围内的数字。
g4 <- expand.grid(yrs, 1:12, 1:30)
s4 <- sort(as.numeric(do.call("sprintf", c("%d%02d%02d", g4))))
6)grep 使用(5)
中的seq5 <- seq(as.numeric(startingdate), as.numeric(endingdate))
d5 <- seq5[ seq5 %/% 100 %% 100 %in% 1:12 & seq5 %% 100 %in% 1:30]
seq5
答案 1 :(得分:0)
这是另一种选择:
date <- unclass(startingdate):unclass(endingdate) %% 30L
month <- rep(1:12, each = 30, length.out = NN <- length(date))
year <- rep(1:(NN %/% 360 + 1), each = 360, length.out = NN)
(当然,如果您希望特定日期为0或特定月份等,我们可以通过添加常量来轻松调整。)