4

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 Answer 1

2

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" 
Sign up to request clarification or add additional context in comments.

4 Comments

Note paste0() is vectorized so it will work with your coulmn
how would this work for those dates that are double digit months e.g. 111960, the column in question has >1000 such date
thanks again for the answer. Could I ask what the ",y" in the line x<-ifelse(nchar(y) == 5,paste0("010",y),paste0("01",y)), does?
"y" is the input vector, so the function paste0 adds "010" to each element in "y"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.