Merge three different columns into a date in R

There is also a simpler solution using lubridate and magrittr:

df$date <- paste(df$year, df$mon, df$day, sep="-") %>% ymd() %>% as.Date()

This worked for me, even though I had days and months written in single (i.e. 1) and double (i.e. 01) digits. Parsing was correct as well.


Try:

  df$date <- as.Date(with(df, paste(year, mon, day,sep="-")), "%Y-%m-%d")
   df$date
  #[1] "1947-01-01" "1947-04-01" "1947-07-01" "1947-10-01" "1948-01-01"
  #[6] "1948-04-01"

Since your year, month and day types are numerical the best function to use is the make_date function from the lubridate package. The tidyverse style solution is therefore

library(tidyverse)
library(lubridate)

data %>%
  mutate(date = make_date(year, month, day))

Tags:

R