Convert integer as “20160119” to different columns of “day” “year” “month”

后端 未结 5 1444
走了就别回头了
走了就别回头了 2020-12-06 15:30

How can I convert a column of integers as dates:

       DATE PRCP
1: 19490101   25
2: 19490102    5
3: 19490118   18
4: 19490119  386
5: 19490202   38
         


        
5条回答
  •  孤街浪徒
    2020-12-06 16:27

    Another option would be to use separate from the tidyr package:

    library(tidyr)
    separate(df, DATE, c('year','month','day'), sep = c(4,6), remove = FALSE)
    

    which results in:

           DATE year month day PRCP
    1: 19490101 1949    01  01   25
    2: 19490102 1949    01  02    5
    3: 19490118 1949    01  18   18
    4: 19490119 1949    01  19  386
    5: 19490202 1949    02  02   38
    

    Two options in base R:

    1) with substr as said by @coffeinjunky in the comments:

    df$year <- substr(df$DATE,1,4)
    df$month <- substr(df$DATE,5,6)
    df$day <- substr(df$DATE,7,8)
    

    2) with as.Date and format:

    df$DATE <- as.Date(as.character(df$DATE),'%Y%m%d')
    df$year <- format(df$DATE, '%Y')
    df$month <- format(df$DATE, '%m')
    df$day <- format(df$DATE, '%d')
    

提交回复
热议问题