0

I have a df with these columns:

     IN_BOLSA    IN_AUXILIOS          IN_OUTRA_REMUNERACAO  
1    NÃO         NÃO                  NÃO                   
2    SIM         NÃO                  NÃO                   
3    NÃO         NÃO                  NÃO                   
4    NÃO         SIM                  NÃO                   
5    SIM         NÃO                  SIM   

I'd like to create a new column that has "SIM" as a value if any of the other three also is "SIM" (and NÃO otherwise) Like this:

     IN_BOLSA    IN_AUXILIOS          IN_OUTRA_REMUNERACAO  NEW_COLUMN
1    NÃO         NÃO                  NÃO                   NÃO
2    SIM         NÃO                  NÃO                   SIM
3    NÃO         NÃO                  NÃO                   NÃO
4    NÃO         SIM                  NÃO                   SIM
5    SIM         NÃO                  SIM                   SIM
thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • I feel like this should be duplicated but I can't find a good example - something like `rowSums(dat == "SIM") > 0` will do it. This one is close to the same logic - https://stackoverflow.com/questions/36930138/how-to-use-a-loop-to-delete-all-rows-with-negative-values-in-r/36930498 – thelatemail Mar 12 '20 at 02:52

1 Answers1

0

We can use rowSums

df$NEW_COLUMN <- c("NAO", "SIM")[(rowSums(df == "SIM") > 0) + 1]
df

#  IN_BOLSA IN_AUXILIOS IN_OUTRA_REMUNERACAO NEW_COLUMN
#1      NÃO         NÃO                  NÃO        NAO
#2      SIM         NÃO                  NÃO        SIM
#3      NÃO         NÃO                  NÃO        NAO
#4      NÃO         SIM                  NÃO        SIM
#5      SIM         NÃO                  SIM        SIM

data

df <- structure(list(IN_BOLSA = structure(c(1L, 2L, 1L, 1L, 2L), 
.Label = c("NÃO", "SIM"), class = "factor"), IN_AUXILIOS = structure(c(1L, 1L, 
1L, 2L, 1L), .Label = c("NÃO", "SIM"), class = "factor"), 
IN_OUTRA_REMUNERACAO = structure(c(1L, 1L, 1L, 1L, 2L), 
.Label = c("NÃO", "SIM"), class = "factor")), class = "data.frame", 
row.names = c("1", "2", "3", "4", "5"))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213