Search code examples
rlistdataframetype-conversionposixlt

Replace characters with dates in dataframe in r


I have a dataframe with dates stored as strings. The conversion with strptime works fine when I test it in the terminal, but when I want to assign the date in the original cell, I get an error:

provided 11 variables to replace 1 variables

This must be due to the fact that the Object created by strptime() POSIXlt is a list.

How can I assign that object into the cell? I later want to order the dataframe by the date column.

I'm sorry that I can't share the code, due to privacy restrictions.

Edit: This snippet should produce the same error

#creating dataframe
x <- c( "20.11.2019 10:12:15", "21.10.2019 10:12:16", "20.10.2019 10:12:20")
y <- c( "1234", "1238", "1250")
df <- data.frame( "date" = x, "id" = y)

df[order(df$date),] #ordering by date

df #showing that dates get ordered 'incorrectly'

df[,1] = strptime(df[,1], "%d.%m.%Y %H:%M:%S") #trying to replace character with dates while converting

#afterwards I want to order them again 'correctly'

Solution

  • Personally I would use dplyr to mutate the values of the original cell. In combination with lubridate it works for me (at least I think this what you wanted):

    df <- df %>% mutate(date =ymd_hms(strptime(date, "%d.%m.%Y %H:%M:%S"))) %>% arrange(date)

                     date   id
    1 2019-10-20 10:12:20 1250
    2 2019-10-21 10:12:16 1238
    3 2019-11-20 10:12:15 1234