1

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'
Arkantos
  • 23
  • 3
  • If you can't share the real data or code, please come up with a toy example that we can play with. Otherwise, we're all just shooting in the dark. Without more context, it's unlikely that people will spend much time trying to help you solve the issue you're having. – ErrorJordan Dec 12 '19 at 16:38
  • 1
    alright, working on it now – Arkantos Dec 12 '19 at 16:42
  • I edited the post now :) – Arkantos Dec 12 '19 at 17:13

2 Answers2

1

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
Annet
  • 846
  • 3
  • 14
  • Thank you so much! This worked just fine after installing the packages. What does the ```%>%``` part do? Edit: here is the answer to that https://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html – Arkantos Dec 12 '19 at 18:29
  • It basically means than. So first it takes the dataframe (specified with df) than does some mutation on that dataframe, which is changing the column. Than it applies the reordening of dataframe basted on the date column. It comes from magrittr: https://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html – Annet Dec 12 '19 at 18:33
1

This simple adjustment also works. Change df[,1] to df$date.

df$date = strptime(df[,1], "%d.%m.%Y %H:%M:%S") 
ErrorJordan
  • 611
  • 5
  • 15
  • Thats very interesting as I always used these interchangably. Why is df$date more flexible? – Arkantos Dec 13 '19 at 19:44
  • I don't know the answer to that question. Usually the `$` operator is considered less flexible and less ideal for production coding. – ErrorJordan Dec 13 '19 at 20:10