assign 1 and 0 values

Dear R users,

I have 4 columns with 0 and 1 values.

 x1   x2   x3   x4
 1    0    0    1
 0    1    1    0
 0    0    0    0 
 0    0    0    1   

Now I want to create the 5th column ( x5) like

 x1   x2   x3   x4  x5
 1    0    0    1    1
 0    1    1    0    1
 0    0    0    0    0
 0    0    0    1    1

I want to create one new column based on my row values. for example, if my one-row has 1 (x1 to x4) then-new the row should assign as 1. If a row does not have 1 then a new row should assign as 0.

please provide some information on that.
Thank You

Here is one method:

library(dplyr,warn.conflicts = FALSE)
DF <- data.frame(x1 =c (1,0,0,0), x2 = c(0,1,0,0), 
                  x3 = c(1,0,0,1), x4 = c(1,1,0,1))
DF %>% rowwise() %>%  
   mutate(x5=as.numeric(any(c_across(x1:x4)==1)))
# A tibble: 4 x 5
# Rowwise: 
     x1    x2    x3    x4    x5
  <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     0     1     1     1
2     0     1     0     1     1
3     0     0     0     0     0
4     0     0     1     1     1
1 Like

This topic was automatically closed 21 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.