-1

I would like to loop over several columns to compare those variables within a data frame.

For example:

df1
| col1     | col2  | col3  |
| -------- | ------|-------|
| First    | PwC   | PwC   |
| Second   | BCG   | BCG   |
| Third    | web   | txt   |

Looking at that example I would like to loop over col2 and col3.

If df1[1,2] == df1[1,3], then write 0 in a new col4, else write 1 in the col4.

Does someone have an idea?

Thanks in advance!

Proki
  • 27
  • 6

1 Answers1

1

We don't need a loop for this. Just create a logical vector and coerce it to binary (as.integer)

df1$col4 <- as.integer(df1$col2 != df1$col3)
akrun
  • 874,273
  • 37
  • 540
  • 662