How to create a new dummy column from multiple dummy columns


Hello RStudio community,
How to create a dummy column from multiple dummy columns. I would like to create a new dummy column (x5) from column x1-x4 in below dataset. In order that x5=1 If any rows has 1, x5=0 if any rows has 0, but not 1, otherwise NA. If anybody can help me. Appreciate it.

data <- data.frame (sn = 1:6,
                    x1 = c(NA,1L,0L,NA,1L,0L),
                    x2 = c(1L,NA,0L,NA,1L,1L),
                    x3 = c(0L,1L,0L,NA,0L,0L),
                    x4 = c(1L,NA,0L,NA,1L,1L)
                    )

Is this what you mean?

library(dplyr)

data <- data.frame (sn = 1:6,
                    x1 = c(NA,1L,0L,NA,1L,0L),
                    x2 = c(1L,NA,0L,NA,1L,1L),
                    x3 = c(0L,1L,0L,NA,0L,0L),
                    x4 = c(1L,NA,0L,NA,1L,1L)
)

data %>%
    rowwise() %>% 
    mutate(x5 = case_when(
        any(across(c(x1:x4))) ~ 1,
        !any(across(c(x1:x4))) ~ 0
    ))
#> # A tibble: 6 × 6
#> # Rowwise: 
#>      sn    x1    x2    x3    x4    x5
#>   <int> <int> <int> <int> <int> <dbl>
#> 1     1    NA     1     0     1     1
#> 2     2     1    NA     1    NA     1
#> 3     3     0     0     0     0     0
#> 4     4    NA    NA    NA    NA    NA
#> 5     5     1     1     0     1     1
#> 6     6     0     1     0     1     1

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

Thank you very much. Ys, it is. In my real data, it is ok with 1s and NAs, but does not take rows with all 0s.

Can you provide a REPRoducible EXample (reprex) for this?

Ys, I have some rows with all 0s, but the new row shows NA. Maybe I need a notation in this syntax to consider 0s too. Thank you again!

That is a textual description, not a reproducible example, please read the guide on the link I gave you and try to provide a reprex.

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.