Create date column from datetime in R

后端 未结 2 1168
走了就别回头了
走了就别回头了 2021-01-29 15:35

I am new to R and I am an avid SAS programmer and am just having a difficult time wrapping my head around R.

Within a data frame I have a date time column formatted as

2条回答
  •  有刺的猬
    2021-01-29 16:27

    Use the lubridate package. For example, if df is a data.frame with a column dt of type POSIXct, then you could:

    df$date = as.Date(as.POSIXct(df$dt, tz="UTC"))
    df$year = year(df$dt)
    df$month = month(df$dt)
    df$day = day(df$dt)
    # and so on...
    

    If your can store your data in a data.table, then this is even easier:

    df[, `:=`(date = as.Date(as.POSIXct(dt, tz="UTC")), year = year(dt), ...)]
    

提交回复
热议问题