Moth Difference with Seq(), Lubridate() and DF

Hi Community

I try to return the difference into the months, the problem its that the second columns do not have all the dates. when i try to run the code, the output is error. Appreciate any help?

Error in mutate():
! Problem while computing
diff.dt = case_when(...). Caused by error in seq.Date()`:
! 'from' must be of length 1

date1 <- c("01-01-2022", "02-01-2022", "01-02-2022", "02-02-2022")
date2 <- c("15-01-2022", "13-02-2022", "", "20-02-2022")
ot <- c("MI", "FA", "SOL", "LA")

df <- data.frame(date2, date1, ot)

df<- df %>%
  mutate(date1 = dmy(date1),
         date2 = dmy(date2),
         diff.dt = case_when(
           !is.na(date2) ~ seq.Date(date2, date1, by = "month"),
           TRUE ~ "NA")
         )

Hello,

I couldn't get ymd() to work with your code sample since your dates are in dmy() format (I get a [All formats failed to parse] error), but you can use an ifelse() statement to get a difference in seconds once that is resolved using as.POSIXct().


library(lubridate)
library(dplyr)

date1 <- c("01-01-2022", "02-01-2022", "01-02-2022", "02-02-2022")
date2 <- c("15-01-2022", "13-02-2022", "", "20-02-2022")
ot <- c("MI", "FA", "SOL", "LA")

df <- data.frame(date2, date1, ot)


df2 <- df %>%
  mutate(
    date1 = ifelse(is.na(date1) ,"", 
 (as.POSIXct(date1, format = "%d-%m-%y"))
 ),
    date2 = ifelse(is.na(date2) ,"", 
 (as.POSIXct(date2, format = "%d-%m-%y"))
 ),
    date3 = ifelse(date2 == "","",(date2-date1)) #This gives time difference in seconds 
         )

Hi Dissipation

I try to get the difference in moths, do you know how could I do this?

A month is not a fixed length of time. How would you fix the length of a month? How many months is 14 days?

1 Like

As mentioned by FJCC, you need to define the month time (30 days for example), and convert all the seconds to days. 14 days in this example would be ~0.47 months (14/30).

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.