【问题标题】:splitting dates in R [duplicate]在R中分割日期[重复]
【发布时间】:2020-04-28 12:55:19
【问题描述】:

我的数据框的时间列如下所示

# time
# %Y-%m-%d
# 2000-01-01
# 2000-01-02
# ...

我想将日期列分成一个年份和一个月份(我不需要天数) 所以输出应该如下所示:

# year  month
# %Y    %m
# 2000  01
# 2000  02
# ...

【问题讨论】:

    标签: r dataframe date


    【解决方案1】:

    lubridate 包中,使用year()month() 函数分别从日期对象中提取它们。

    library(data.table)
    library(lubridate)
    
    DT <- as.data.table(yourDataFrame)
    
    DT[, Date := ymd(time)]
    DT[, year := year(Date)]
    DT[, month := month(Date)]
    

    【讨论】:

      【解决方案2】:

      基础R:

      # data:
      time<-seq.Date(from = as.Date("2000/1/1"),to=as.Date("2000/5/1"),by="days")
      df<-data.frame(ID=1:length(time), time= time)
      
      # months
      df$month<-month(df$time)
      # or:
      df$month.name<-months(df$time)
      
      
      df
      
      
      

      【讨论】:

        【解决方案3】:

        你可以试试separate,例如,

        library(dplyr)
        library(tidyr)
        
        df %>% separate(d,c("year","month"),extra = "drop")
        

        给了

        > df %>% separate(d,c("year","month"),extra = "drop")
          year month
        1 2020    01
        2 2020    02
        

        数据

        df <- data.frame(d = c("2020-01-01","2020-02-01"))
        

        【讨论】:

        • 或者使用extract和ini separate,如果你只指定两列,还有extra = 'drop'的选项
        • @akrun 非常感谢!现在我了解了更多关于separate(我之前没有使用dplyr)的知识:P
        猜你喜欢
        • 2018-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-13
        • 1970-01-01
        • 1970-01-01
        • 2023-04-08
        • 2017-02-02
        相关资源
        最近更新 更多