假设所有年份都是非闰年,将年份转换为日期

Convert day of year to date assuming all years are non-leap years

我有一个以年份和年份为列的 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)

我需要日期来指定一个月中的某一天是否在第一天 一半(i.e.d 天 <= 15)或第二季度(天 > 15)。我使用以下 执行此操作的脚本:

dat2 <- dat1 %>% mutate(twowk = month*2 - (as.numeric(format(date,"%d")) <= 15))

为了让我 运行 上述行,我需要生成 date 以及我的问题。

可能的解决方案:

dat$dates <- as.Date(paste0(dat$year,'-',
                            format(strptime(paste0('1981-',dat$day), '%Y-%j'),
                                   '%m-%d'))
                     )

这是做什么的:

  • 使用 strptime(paste0('1981-',dat$day), '%Y-%j') 可以获得 non-leap 年的日期。
  • 通过使用 '%m-%d' 将其嵌入 format 中,您可以提取月份和月份中的日期。
  • paste 连同 year 列中的年份并将其包装在 as.Date 中以获得 non-leap 年份日期。