简体   繁体   中英

Convert data to date, month, year in lubridate in R

I have a dataframe with a column with dates, the column is named dateDecision . They are in the format 1970/01/01 . I am trying to split the date into year , month and date columns. I used the following code

df %>% mutate(year = lubridate::year(dateDecision), 
                month = lubridate::month(dateDecision), 
                day = lubridate::day(dateDecision))

I get an error saying Error in as.POSIXlt.character(x, tz = tz(x)): character string is not in a standard unambiguous format

When I use dput(head(df,10)), this is the output

structure(list(term = c("1791", "1791", "1791", "1791", "1791", 
"1792", "1792", "1792", "1792", "1792"), dateDecision = c("8/3/1791", 
"8/3/1791", "8/3/1791", "8/3/1791", "8/3/1791", "8/11/1792", 
"8/11/1792", "8/11/1792", "8/11/1792", "8/11/1792"), decisionType = c("6", 
"6", "6", "6", "6", "8", "8", "8", "8", "8"), dateArgument = c("8/2/1791", 
"8/2/1791", "8/2/1791", "8/2/1791", "8/2/1791", "8/9/1792", "8/9/1792", 
"8/9/1792", "8/9/1792", "8/9/1792")), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

How do I fix this?

You need to convert you dateDecision column to a date first using lubridate

df %>% mutate(dateDecision=lubridate::mdy(dateDecision),
              year = lubridate::year(dateDecision), 
              month = lubridate::month(dateDecision), 
              day = lubridate::day(dateDecision))

First use anytime::anydate() library to convert you dateDecision column to a date:

library(anytime)
    date <- "1970/01/01"
    anytime::anydate(date)
    [1] "1970-01-01"

Then run your mutate. You can use tk_augment_timeseries_signature() from timetk as well and only select only year , month and date columns.

library(timetk)
library(tidyverse)

# make some reproducible data
dates <-
    seq(as.Date('2019-01-01'), as.Date('2019-12-31'), by = 'days') 

dates <- as_tibble(dates)

#add the time signature features including year, month, day, day of week, day of month, #day of year, hour, minute, second to the input data

dates %>% 
tk_augment_timeseries_signature()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM