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
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')