Convert integer as "20160119" to different columns of "day" "year" "month"
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
to a table like this:
days month years PRCP
We can use extract
library(tidyr)
extract(df, DATE, into=c('YEAR', 'MONTH', 'DAY'),
'(.{4})(.{2})(.{2})', remove=FALSE)
# 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
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