【问题标题】:Convert day of year to date assuming all years are non-leap years假设所有年份都是非闰年,则将日期转换为日期
【发布时间】: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 ;)

标签: r date dataframe as.date


【解决方案1】:

一个可能的解决方案:

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

这是做什么的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 2020-06-04
    相关资源
    最近更新 更多