Create a new variable based on other columns values

Viewed 205

I have a paneldata dataframe structure, something like this:

df <- data.frame("id" = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3),          
             "Status_2014" = c(1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0),
             "Status_2015" = c(0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0),
             "Status_2016" = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))

I want to generate a new dummy variable, that takes the value 1, if the rows contains 1 in any of the three columns or otherwise 0 if not. It should end up like this:

df <- data.frame("id" = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3),          
             "Status_2014" = c(1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0),
             "Status_2015" = c(0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0),
             "Status_2016" = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), 
             "Final_status" = c(1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0))

Can anyone help me achieve this?
2 Answers

We can use if_any on the columns that starts_with 'Status', to check for any 1 value in a row and it returns TRUE if there is one or else FALSE which is coerced to binary with as.integer/+

library(dplyr)
df %>%
   mutate(Final_status = +(if_any(starts_with('Status'),  ~ . ==1)))

-outptu

id Status_2014 Status_2015 Status_2016 Final_status
1   1           1           0           0            1
2   1           1           0           0            1
3   1           1           0           0            1
4   1           1           0           0            1
5   2           0           1           0            1
6   2           0           1           0            1
7   2           0           1           0            1
8   2           0           1           0            1
9   3           0           0           0            0
10  3           0           0           0            0
11  3           0           0           0            0
12  3           0           0           0            0

Or using rowSums from base R

df$Final_status <- +(rowSums(df[-1] > 0) > 0)
Related