Merge three different columns into a date in R

前端 未结 4 778
梦毁少年i
梦毁少年i 2020-12-08 16:38

Right now, I am having 3 separate columns as year, month, and day in a data file in R. How do I merge these three columns into just one column and make R understand that it

4条回答
  •  渐次进展
    2020-12-08 17:07

    Or you could use the lubridate package, which makes working with dates and times in R much easier in general.

    e.g.

    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 could be "19470101", "1947-01-01", "1947/01/01", etc. Or there is also mdy and dmy if the elements are ordered differently. You can also optionally specify a time zone.

提交回复
热议问题