0

I have the following data frame in R, and I need to update the values in column feat_4 to 1 if any of the other 3 feature columns (feat_1, feat_2, and feat_3) contains a 1:

Name  feat_1  feat_2  feat_3   feat_4
Tom    0        0       0        0
David  1        0       1        0
Tim    0        1       0        0

I know I can do this by using a for-loop like this, but is there a more efficient/vectorized way of doing it? I could have more columns than what is being show above. Thank you for help!

for (row in 1:nrow(df)) {
  if (any(df[row,2:4] == 1)) {
     df$feat_4 = 1
  }
}
thelatemail
  • 91,185
  • 12
  • 128
  • 188
TonyW
  • 18,375
  • 42
  • 110
  • 183
  • 3
    Pretty sure this is a duplicate - `pmin(1, rowSums(dat[2:4]))` or something similar should do it. – thelatemail Nov 29 '16 at 23:52
  • 2
    Maybe http://stackoverflow.com/questions/28233561/finding-rows-containing-a-value-or-values-in-any-column or http://stackoverflow.com/questions/38089453/search-values-across-all-columns-in-r-data-frame – thelatemail Nov 30 '16 at 00:03

0 Answers0