Home > Mobile >  Why does diff.time Return NA values, console shows no error.?
Why does diff.time Return NA values, console shows no error.?

Time:07-10

I am here trying to calculate the time difference between two date formats, first, I have been faced with various errors such as

  • as.POSIXlt.character : character string is not in a standard unambiguous format
  • Values unable to parse
  • NA values added by coercion

however, with trials, I have reached this next line of code that runs with no errors or warnings but the return values are all NA

Rides_cleaned <-
  Rides %>% 
  drop_na() %>% 
  distinct() %>% 
  mutate(rideduration=difftime(as.numeric(as.POSIXct(ended_at,format = "%m/%d/%Y %H:%M:%S %p")),
                               as.numeric(as.POSIXct(started_at,format = "%m/%d/%Y %H:%M:%S %p")), units = "mins"))

enter image description here

CodePudding user response:

Make sure to use the correct date format, as.numeric isn't needed either:

Rides <- data.frame(started_at="6/4/21 7:45",ended_at="6/4/21 7:46")

Rides %>% 
  drop_na() %>% 
  distinct() %>% 
  mutate(rideduration=difftime(as.POSIXct(ended_at,format = "%m/%d/%y %H:%M"), 
                               as.POSIXct(started_at,format = "%m/%d/%y %H:%M"), 
                               units = "mins"))

#   started_at    ended_at rideduration
#1 6/4/21 7:45 6/4/21 7:46       1 mins
  • Related