Convert a string into dates using R

Viewed 129

I have a column of dates written as monthyear in the format: 11960 - this would be Jan 1960 121960 - this would be Dec 1960

I would like to convert this column into a day-month-year format assuming the first of the month as each date.

I have tried (using one number as an example as opposed to dt$dob)

x <- sprintf("%08d%", 11960) and then x <- as.date(x, format = "%d%m%Y)

but this gives me NAs as I assume it doesn't like the 00 at the start

So I tried pasting 01 to each value but this pastes it to the end (R noob here). I was thinking maybe posting 01 to the start and then using the sprintf function may work still:

  • paste 01 to start of 11960 = 011960
  • sprintf("%08d%", 011960) to maybe give 0101960?
  • Then use as.Date to convert?

Many thanks for your help

1 Answers

i used paste0() instead of sprintf, but it seems it works.

> x<-paste0("010",11960)
> x
[1] "01011960"
> as.Date(x , format = "%d%m%Y" )
[1] "1960-01-01"


EDIT for 2 digit months i use ifelse() and nchar()

y<-c(11960,11970,11980, 111960,111970,111980)
x<-ifelse(nchar(y) == 5,paste0("010",y),paste0("01",y))

> x
[1] "01011960" "01011970" "01011980" "01111960" "01111970" "01111980"

as.Date(x , format = "%d%m%Y" )
[1] "1960-01-01" "1970-01-01" "1980-01-01" "1960-11-01" "1970-11-01" "1980-11-01"

Related