【问题标题】:In R: Conditionally changing dates to prior years在 R 中:有条件地将日期更改为往年
【发布时间】:2021-06-16 17:21:30
【问题描述】:

我有一份公司会计年度的日期列表。我想将 1 月 1 日至 5 月 31 日之间的所有日期转换为一个新变量,它表示它属于上一年。我也有介于 6 月 1 日至 12 月 31 日之间的日期,我希望这些年保持不变。 我们想要的示例:

   date       year
2010-05-31    2009
2015-03-31    2014
2007-04-30    2006
2011-08-31    2011
2002-11-30    2002

非常感谢您的帮助!谢谢!

【问题讨论】:

    标签: r date


    【解决方案1】:

    你可以在base R:

    > df <- data.frame(date = as.Date(c("2010-05-31", "2015-03-31", "2007-04-30", "2011-08-31", "2002-11-30")))
    > df$year <- as.numeric(format(df$date, "%Y")) - (as.numeric(format(df$date, "%m")) < 6)
    > df
            date year
    1 2010-05-31 2009
    2 2015-03-31 2014
    3 2007-04-30 2006
    4 2011-08-31 2011
    5 2002-11-30 2002
    

    如果月份在六月之前,则最后一年是减去 1 的年份。

    【讨论】:

      【解决方案2】:

      使用dplyrlubridate

      library(dplyr)
      library(lubridate)
      
      df %>% mutate(year =  year(date) - as.integer(month(date) <= 5))
      
      #        date year
      #1 2010-05-31 2009
      #2 2015-03-31 2014
      #3 2007-04-30 2006
      #4 2011-08-31 2011
      #5 2002-11-30 2002
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多