D. Studer
D. Studer

Reputation: 1875

r: add day to a date-variable under a certain condition

I was trying to add one day to the to-variable - but only if from is not missing:


df <- data.frame(from = c("2020-01-01", "2020-02-01", ""),
                 to   = c("2020-01-05", "2020-02-20", "2020-03-04"))

df <- df %>% mutate(
                    from = as.Date(from),
                    to = as.Date(to),
                    to = ifelse(!is.na(from), to + 1, to)
                   )

df

Obviously, this doesn't work :(. Can anyone tell me how to do it?

Upvotes: 0

Views: 250

Answers (2)

akrun
akrun

Reputation: 887028

We can also do

library(lubridate)
library(dplyr)
df %>%
      mutate(across(everything(), ymd), 
             to = case_when(!is.na(from)~ to+1, TRUE ~ to))

-output

#       from         to
#1 2020-01-01 2020-01-06
#2 2020-02-01 2020-02-21
#3       <NA> 2020-03-04

Upvotes: 1

Duck
Duck

Reputation: 39595

Try this. The function ifelse() uses to transform dates to numbers. Instead you can use if_else() from dplyr. Here the code:

#Data
df <- data.frame(from = c("2020-01-01", "2020-02-01", ""),
                 to   = c("2020-01-05", "2020-02-20", "2020-03-04"))

#Variables
df <- df %>% mutate(
  from = as.Date(from),
  to = as.Date(to),
  to = if_else(!is.na(from), to + 1, to)
)
#Output
df

Output:

df
        from         to
1 2020-01-01 2020-01-06
2 2020-02-01 2020-02-21
3       <NA> 2020-03-04

Upvotes: 1

Related Questions