Resulting state from 2 signals

How can I get resulting state from 2 vectors - one vector is turning on and another one is turning off state (need to calculate results in column ~state). If no signals in any column - should take previous state


tribble(
  ~signal_on, ~signal_off,~state,
  1,0,1,
  0,0,1,
  1,0,1,
  1,1,0,
  0,1,0,
  1,0,1,
  1,0,1,
  0,0,1,
  0,0,1,
  0,1,0,
  1,0,1
)

Assuming that off takes precedence over on when they both occur (because that is not obvious), then something like this might work:

library(tidyverse)

df <- tribble(
    ~signal_on, ~signal_off,
    1,0,
    0,0,
    1,0,
    1,1,
    0,1,
    1,0,
    1,0,
    0,0,
    0,0,
    0,1,
    1,0
)


df %>% 
    mutate(state = case_when( signal_off == 1 ~ 0,
                                                signal_on == 1 ~ 1)) %>% 
    mutate(state = zoo::na.locf(state) )
#> # A tibble: 11 x 3
#>    signal_on signal_off state
#>        <dbl>      <dbl> <dbl>
#>  1         1          0     1
#>  2         0          0     1
#>  3         1          0     1
#>  4         1          1     0
#>  5         0          1     0
#>  6         1          0     1
#>  7         1          0     1
#>  8         0          0     1
#>  9         0          0     1
#> 10         0          1     0
#> 11         1          0     1

Created on 2019-10-04 by the reprex package (v0.3.0)

1 Like

I didn't knew about zoo::na.locf() but for this simple case you can also do it with just the tidyverse

library(tidyverse)

df <- tribble(
    ~signal_on, ~signal_off,
    1,0,
    0,0,
    1,0,
    1,1,
    0,1,
    1,0,
    1,0,
    0,0,
    0,0,
    0,1,
    1,0
)


df %>% 
    mutate(state = case_when( signal_off == 1 ~ 0,
                              signal_on == 1 ~ 1)) %>% 
           fill(state, .direction = "down")
#> # A tibble: 11 x 3
#>    signal_on signal_off state
#>        <dbl>      <dbl> <dbl>
#>  1         1          0     1
#>  2         0          0     1
#>  3         1          0     1
#>  4         1          1     0
#>  5         0          1     0
#>  6         1          0     1
#>  7         1          0     1
#>  8         0          0     1
#>  9         0          0     1
#> 10         0          1     0
#> 11         1          0     1
1 Like

The fewer dependencies, the better :). The .direction="down" is a bit counterintuitive to me, aren't we looking up the dataframe to fill the values?

Well I think is a little bit subjective, I think it depends on the way you conceptualize it in your head, I see it as the direction on witch I'm filling stuff not from where I'm taking the values, because I assume is the previous one relative to the direction you are going.

1 Like

Thanks to everybody! Did not know about case_when

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