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

后端 未结 5 1443
走了就别回头了
走了就别回头了 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

    Here's another way using regular expressions:

    df <- read.table(header=T, stringsAsFactors=F, text="
    DATE PRCP
    19490101   25
    19490102    5
    19490118   18
    19490119  386
    19490202   38")
    dates <- as.character(df$DATE)
    res <- t(sapply(regmatches(dates, regexec("(\\d{4})(\\d{2})(\\d{2})", dates)), "[", -1))
    res <- structure(as.integer(res), .Dim=dim(res)) # make them integer values
    cbind(df, setNames(as.data.frame(res), c("Y", "M", "D"))) # combine with original data frame
    #       DATE PRCP    Y  M  D
    # 1 19490101   25 1949 01 01
    # 2 19490102    5 1949 01 02
    # 3 19490118   18 1949 01 18
    # 4 19490119  386 1949 01 19
    # 5 19490202   38 1949 02 02
    

提交回复
热议问题