【问题标题】:Change from integer to date in R在R中从整数更改为日期
【发布时间】:2021-08-12 03:53:14
【问题描述】:

我有下一个数据框,我想将月份和年份变量的格式更改为日期

data.frame':    450 obs. of  3 variables:
 $ month : int  11 12 1 2 3 4 5 6 7 8 ...
 $ year  : int  2010 2010 2011 2011 ...
 $ num3  : num  157 124.3 196.5 197 70.8 ... 

我试了一下,但我得到一个错误:

as.Date(df$month, format="%m")

Error in as.Date.numeric(df$month, format = "%m") : 
  'origin' must be supplied

我该如何解决?另外,我想用月份和年份创建新变量

【问题讨论】:

    标签: r date lubridate


    【解决方案1】:

    似乎很清楚,您想要的不仅仅是月份。因此,您可以同时使用月份和年份,但您还需要一个完整的月份,所以我们假设第 15 天。

       df$real_Date <- as.Date( paste(df$year,df$month, 15, sep="-") )
    
    > month <- scan( text=" 11 12 1 2 3 4 5 6 7 8")
    Read 10 items
    > year <- scan( text="  2010 2010 2011 2011 2011 2011 2011 2011 2011 2011")
    Read 10 items
    > num3  <- scan( text=" 157 124.3 196.5 197 70.8 ")
    Read 5 items
    > df <- data.frame(month,year,num3)
    > df
       month year  num3
    1     11 2010 157.0
    2     12 2010 124.3
    3      1 2011 196.5
    4      2 2011 197.0
    5      3 2011  70.8
    6      4 2011 157.0
    7      5 2011 124.3
    8      6 2011 196.5
    9      7 2011 197.0
    10     8 2011  70.8
    > df$real_Date <- as.Date( paste(df$year,df$month, 15, sep="-") )
    > df
       month year  num3  real_Date
    1     11 2010 157.0 2010-11-15
    2     12 2010 124.3 2010-12-15
    3      1 2011 196.5 2011-01-15
    4      2 2011 197.0 2011-02-15
    5      3 2011  70.8 2011-03-15
    6      4 2011 157.0 2011-04-15
    7      5 2011 124.3 2011-05-15
    8      6 2011 196.5 2011-06-15
    9      7 2011 197.0 2011-07-15
    10     8 2011  70.8 2011-08-15
    

    【讨论】:

    • 感谢您的回答,但我的数据集没有日期列,这很奇怪,但确实如此。
    【解决方案2】:

    我们也可以使用来自base RISOdate

    df$date <-  with(df, as.Date(ISOdate(year, month, 1)))
    

    数据

    df <- data.frame(month = c(11, 12, 1, 2), year = c(2010, 2010, 2011, 2011))
    

    【讨论】:

      【解决方案3】:

      我们可以使用来自lubridate 包的make_date

      library(dplyr)
      library(lubridate)
      df %>% 
        mutate(date = make_date(year, month))
      

      输出:

        month  year  num3 date      
        <dbl> <dbl> <dbl> <date>    
      1    11  2010  157  2010-11-01
      2    12  2010  124. 2010-12-01
      3     1  2011  196. 2011-01-01
      4     2  2011  197  2011-02-01
      

      【讨论】:

        猜你喜欢
        • 2022-01-22
        • 2017-04-12
        • 1970-01-01
        • 2018-08-14
        • 1970-01-01
        • 2019-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多