【发布时间】:2018-08-20 09:10:01
【问题描述】:
我有一个带有年份和年份的 df 作为列:
dat <- data.frame(year = rep(1980:2015, each = 365), day = rep(1:365,times = 36))
请注意,我假设一年有 365 天,即使是闰年。我需要生成两件事:
1) 月 2) 日期
我这样做了:
# this tells me how many days in each month
months <- list(1:31, 32:59, 60:90, 91:120, 121:151, 152:181, 182:212, 213:243, 244:273, 274:304, 305:334, 335:365)
library(dplyr)
# this assigns each day to a month
dat1 <- dat %>% mutate(month = sapply(day, function(x) which(sapply(months, function(y) x %in% y))))
我想生成第三列,它是year,month,day 格式的日期。
但是,由于我假设所有年份都是非闰年,因此我需要确保我的日期也反映了这一点,即不应有日期为 2 月 29 日。
我需要生成日期的原因是因为我想生成数字 一年的 15 天。一年有24个15天的周期
1st Jan - 15th Jan: 1 period
16th Jan- 31st Jan: 2 period
1st Feb - 15th Feb: 3 period....
16th till 31st dec: 24th period)
我需要日期来指定一个月中的某一天是否在第一天 一半(即天 15)。我使用以下 执行此操作的脚本:
dat2 <- dat1 %>% mutate(twowk = month*2 - (as.numeric(format(date,"%d")) <= 15))
为了让我在上面的行中运行,我需要生成 date 并因此产生我的问题。
【问题讨论】:
-
My answer to your previous question 在这里似乎也很重要。
-
谢谢。是的,我已经使用了您对我上一篇文章的解决方案中的最后一点问题。我唯一没有的是将一年中的日期转换为日期。现在,我将以下答案结合到您的解决方案中以获得我想要的。
-
下面的答案还将一年中的某一天转换为可解析格式的值序列,但改用
strptime;)