Combine three different columns in a date in R

Right now I have 3 separate columns like year, month and day in the data file in R. How to combine these three columns into one column and make R understand that this is a date?

Here's what it looks like now.

year mon day gnp 1947 1 1 238.1 1947 4 1 241.5 1947 7 1 245.6 1947 10 1 255.6 1948 1 1 261.7 1948 4 1 268.7 
+5
source share
2 answers

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" 
+9
source

Or you can use the lubridate package, which simplifies working with dates and times in R.

eg.

 df$date <- with(df, ymd(sprintf('%04d%02d%02d', year, mon, day))) df$date # [1] "1947-01-01 UTC" "1947-04-01 UTC" "1947-07-01 UTC" "1947-10-01 UTC" # [5] "1948-01-01 UTC" "1948-04-01 UTC" 

The ymd function takes a string representing Year, Month, and Day, which can be "19470101", "1947-01-01", "1947/01/01", etc. In addition, there are also mdy and dmy if the elements are ordered differently. You can also specify the time zone.

+1
source

Source: https://habr.com/ru/post/1204542/


All Articles