I'd like a new column in a data.frame to indicate whether, for each row, the number "2" appears in certain other columns. Here's a simple version that works for a small data.frame:
df <- data.frame(mycol.1 = 1:5, mycol.2= 5:1, other.col = -2:2)
df$mycols.contain.two <- df$mycol.1 ==2 | df$mycol.2 ==2
df
mycol.1 mycol.2 other.col mycols.contain.two
1 1 5 -2 FALSE
2 2 4 -1 TRUE
3 3 3 0 FALSE
4 4 2 1 TRUE
5 5 1 2 FALSE
Now suppose the data.frame has 50 columns, and I want the new column to indicate whether any of the columns beginning with "mycol" contain a "2" in each row, without having to use the "|" symbol 49 times. I assume there's an elegant dplyr answer using starts_with()
, but I can't figure out the syntax.