【问题标题】:Date from Character and Numeric Columns in RR中字符和数字列的日期
【发布时间】:2020-09-12 00:47:14
【问题描述】:

我有一个格式的数据集。如何将这些组合成日期格式列?

year   mon  day  

1997    Jul   3   
1997    Jul   1   
1997    Sep   10   
1997    Sep   1     
1998    Oct   10      

【问题讨论】:

    标签: r date data-manipulation


    【解决方案1】:

    您可以将 3 列一起paste 并使用as.Date 将其转换为日期:

    df <- transform(df, date = as.Date(paste(year, mon, day), '%Y %b %d'))
    

    也可以从lubridate 使用ymd。

    library(dplyr)
    library(lubridate)
    
    df %>% mutate(date = ymd(paste(year, mon, day)))
    
    #  year mon day       date
    #1 1997 Jul   3 1997-07-03
    #2 1997 Jul   1 1997-07-01
    #3 1997 Sep  10 1997-09-10
    #4 1997 Sep   1 1997-09-01
    #5 1998 Oct  10 1998-10-10
    

    数据

    df <- structure(list(year = c(1997L, 1997L, 1997L, 1997L, 1998L), mon = c("Jul", 
    "Jul", "Sep", "Sep", "Oct"), day = c(3L, 1L, 10L, 1L, 10L)), 
    class = "data.frame", row.names = c(NA, -5L))
    

    【讨论】:

      【解决方案2】:

      与@Ronak Shah 类似的答案,使用anytime 包

      library(dplyr)
      library(anytime)
      library(stringr)
      df %>% 
        mutate(year_mon_date = anydate(str_c(V1, V2, V3)))
                 
      #     V1  V2 V3 year_mon_date
      # 1 1997 Jul  3    1997-07-03
      # 2 1997 Jul  1    1997-07-01
      # 3 1997 Sep 10    1997-09-10
      # 4 1997 Sep  1    1997-09-01
      # 5 1998 Oct 10    1998-10-10 
      

      数据

      structure(list(V1 = c(1997L, 1997L, 1997L, 1997L, 1998L), V2 = c("Jul", 
      "Jul", "Sep", "Sep", "Oct"), V3 = c(3L, 1L, 10L, 1L, 10L)), class = "data.frame", row.names = c(NA, 
      -5L))
      

      【讨论】:

      • 你使用了str_c(),但是你没有加载stringr。
      • 我已经添加了。谢谢@Darren Tai,亲爱的。
      【解决方案3】:

      您可以从lubridate 使用make_date()。

      library(dplyr)
      library(lubridate)
      
      df %>%
        mutate(date = make_date(year, match(mon, month.abb), day))
      
      #   year mon day       date
      # 1 1997 Jul   3 1997-07-03
      # 2 1997 Jul   1 1997-07-01
      # 3 1997 Sep  10 1997-09-10
      # 4 1997 Sep   1 1997-09-01
      # 5 1998 Oct  10 1998-10-10
      

      其中month.abb 是一个内置向量,用于存储英文月份名称的缩写。


      数据

      df <- structure(list(year = c(1997L, 1997L, 1997L, 1997L, 1998L), mon = c("Jul", 
      "Jul", "Sep", "Sep", "Oct"), day = c(3L, 1L, 10L, 1L, 10L)), 
      class = "data.frame", row.names = c(NA, -5L))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        • 2021-12-18
        • 2021-02-07
        • 2021-03-07
        • 2021-01-18
        • 1970-01-01
        相关资源
        最近更新 更多