Replace a column values based on two date columns

Hi, I would like to replace values of x1 column to 0 or NA if dat1 >date2 if somebody can help me. Appreciate it.

data <- data.frame(x1 = 1:10,
                    date1 = c("2020-01-25", "2021-02-10","2021-03-15","2020-04-09","2021-05-11","2020-06-07","2021-08-08", NA,"2020-10-18", "2021-11-11"),
                    x3 = c(" ", "B", "A", "F","F", " "," ", " "," "," "),
                    date2 = c("2021-01-25", "2022-02-10","2020-03-15","2021-04-09","2020-05-11",NA,"2020-09-08", NA,"2021-05-18", "2020-10-11"),
                    x4 = factor(c("B", "B", "A", "F", "A", "B", "A", "B","A", "B")),
                    stringsAsFactors = FALSE)

This version returns zero if date1 > date2 and NA if either date is NA. Is that what you want?

library(dplyr)

data <- data.frame(x1 = 1:10,
                   date1 = c("2020-01-25", "2021-02-10","2021-03-15","2020-04-09","2021-05-11","2020-06-07","2021-08-08", NA,"2020-10-18", "2021-11-11"),
                   x3 = c(" ", "B", "A", "F","F", " "," ", " "," "," "),
                   date2 = c("2021-01-25", "2022-02-10","2020-03-15","2021-04-09","2020-05-11",NA,"2020-09-08", NA,"2021-05-18", "2020-10-11"),
                   x4 = factor(c("B", "B", "A", "F", "A", "B", "A", "B","A", "B")),
                   stringsAsFactors = FALSE)
data <- data |> mutate(date1=as.Date(date1),
                       date2=as.Date(date2),
                       x1=ifelse(date1 > date2,0,x1))
data
#>    x1      date1 x3      date2 x4
#> 1   1 2020-01-25    2021-01-25  B
#> 2   2 2021-02-10  B 2022-02-10  B
#> 3   0 2021-03-15  A 2020-03-15  A
#> 4   4 2020-04-09  F 2021-04-09  F
#> 5   0 2021-05-11  F 2020-05-11  A
#> 6  NA 2020-06-07          <NA>  B
#> 7   0 2021-08-08    2020-09-08  A
#> 8  NA       <NA>          <NA>  B
#> 9   9 2020-10-18    2021-05-18  A
#> 10  0 2021-11-11    2020-10-11  B

Created on 2022-03-16 by the reprex package (v2.0.1)

1 Like

Ys, that is what I wanted. Thank you very much.

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.