0

I have a data frame with a variable listing dates when event X took place for each individual. That date represents the first day of an event which can last up to a certain number of days. I have another variable Z, which is also a date. I want to see if date Z crosses over with date X + the potential range and create a New Variable listing "Cross_Over" and "No_Cross_Over".

The below appears to work but is very laborious. Is there a quicker way to do this?

df$NewVar <- ifelse(df$X == d1$Z | df$X == df$Z -2 | df$X == df$Z -1| df$X == df$Z +1| df$X == df$Z +2, "Cross_OVer", "No_Cross_Over")
Clemsang
  • 5,053
  • 3
  • 23
  • 41
  • 1
    How about `range <- 2; ifelse(abs(df$X - df$Z) <= range, 'crossover', 'no crossover')`? – Allan Cameron May 23 '22 at 12:40
  • It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick May 23 '22 at 12:49

1 Answers1

0

You could do something like this made-up example:

library(tidyverse)

# Made-up data
sample_data <- tribble(~x, ~range, ~z,
        "2022-01-01", 2, "2022-01-02",
        "2022-01-01", 3, "2022-01-10",
        "2022-01-10", 10, "2022-01-15",
        "2022-01-31", 5, "2022-02-02",
        "2022-01-31", 3, "2022-02-04",
        "2022-02-28", 2, "2022-03-01"
        )|> 
  mutate(across(c(x, z), as.Date))

# Actual code
sample_data |> 
  mutate(cross = if_else(z >= x & z <= x + range, "Cross_Over", "No_Cross_Over"))
#> # A tibble: 6 × 4
#>   x          range z          cross        
#>   <date>     <dbl> <date>     <chr>        
#> 1 2022-01-01     2 2022-01-02 Cross_Over   
#> 2 2022-01-01     3 2022-01-10 No_Cross_Over
#> 3 2022-01-10    10 2022-01-15 Cross_Over   
#> 4 2022-01-31     5 2022-02-02 Cross_Over   
#> 5 2022-01-31     3 2022-02-04 No_Cross_Over
#> 6 2022-02-28     2 2022-03-01 Cross_Over

Created on 2022-05-23 by the reprex package (v2.0.1)

Carl
  • 4,232
  • 2
  • 12
  • 24