I have data that looks like this:
df <- read.table(tc <- textConnection("
var1 var2 var3 var4
1 1 7 NA
4 4 NA 6
2 NA 3 NA
4 4 4 4
1 3 1 1"), header = TRUE); close(tc)
I'm trying to create a new column that returns 1 if there's a match or 0 if none.
My non-working code looks like this:
df$var5 = ifelse("1" %in% df$var1,1,
ifelse("1" %in% df$var2,1,
ifelse("1" %in% df$var3,1,
ifelse("1" %in% df$var4,1,0))))
giving me a table:
var1 var2 var3 var4 var5
1 1 7 NA 1
4 4 NA 6 1
2 NA 3 NA 1
4 4 4 4 1
1 3 1 1 1
The table I actually want should look like
var1 var2 var3 var4 var5
1 1 7 NA 1
4 4 NA 6 0
2 NA 3 NA 0
4 4 4 4 0
1 3 1 1 1
I've looked at the posts:
ifelse not working as expected in R
and
Loop over rows of dataframe applying function with if-statement
but I couldn't get any answer to my problem.