Home > Net >  How can i check if a condition is satisfied with forward steps in different columns in R?
How can i check if a condition is satisfied with forward steps in different columns in R?

Time:09-21

i have a data frame in R that looks like this :

library(tidyverse)
df = tibble(Date = seq(as.Date("2022/1/1"), by = "day", length.out = 5),
              y = c(-0.0169518377693283,-0.0272755133312903,0.166639806607574,0.0786074354127284,-0.0689321729520651),
              a = rep(-0.1377444258,5),
              b = rep(0.137742579))
options(pillar.sigfig=7)

# A tibble: 5 x 4
  Date                 y          a         b
  <date>           <dbl>      <dbl>     <dbl>
1 2022-01-01 -0.01695184 -0.1377444 0.1377426
2 2022-01-02 -0.02727551 -0.1377444 0.1377426
3 2022-01-03  0.1666398  -0.1377444 0.1377426
4 2022-01-04  0.07860744 -0.1377444 0.1377426
5 2022-01-05 -0.06893217 -0.1377444 0.1377426

i want to check in one of column if the value of a in 2022/1/1 is less than the value of y on 2022/1/3 and in another column to check if the value o b on 2022/1/1 is greater than the value of y on 2022/1/3.

ideally i want the resulted data frame to like look like this :

# A tibble: 5 x 6
  Date                 y          a         b checkdown checkup
  <date>           <dbl>      <dbl>     <dbl> <lgl>     <lgl>  
1 2022-01-01 -0.01695184 -0.1377444 0.1377426 TRUE      FALSE   
2 2022-01-02 -0.02727551 -0.1377444 0.1377426 TRUE      TRUE   
3 2022-01-03  0.1666398  -0.1377444 0.1377426 TRUE      TRUE  
4 2022-01-04  0.07860744 -0.1377444 0.1377426          
5 2022-01-05 -0.06893217 -0.1377444 0.1377426       

how can i do this in R ? Is the rollaplyr useful here ?

CodePudding user response:

I think this is what you want, using dplyr::lead and dplyr:lag

df$checkdown<-(df$a<lead(df$y, n=2))
df$checkup<-(df$b>lead(df$y, n=2))

  Date             y      a     b checkdown checkup
  <date>       <dbl>  <dbl> <dbl> <lgl>     <lgl>  
1 2022-01-01 -0.0170 -0.138 0.138 TRUE      FALSE  
2 2022-01-02 -0.0273 -0.138 0.138 TRUE      TRUE   
3 2022-01-03  0.167  -0.138 0.138 TRUE      TRUE   
4 2022-01-04  0.0786 -0.138 0.138 NA        NA     
5 2022-01-05 -0.0689 -0.138 0.138 NA        NA 
  • Related