Try this. To keep the NA
s add another ifelse
which checks for NA
s in col1
and keeps them.
df <- structure(list(col1 = c(
NA, "drink", "drink", "drink", "eat",
"eat", "eat", NA, "eat", "drink"
), col2 = c(
"yes", "yes", "no",
"no", "yes", "yes", "yes", "yes", "no", "yes"
), newcolumn = c(
NA,
"1", "0", "0", "1", "1", "1", NA, "1", "1"
)), row.names = c(
NA,
-10L
), class = "data.frame")
df$newcolumn <- ifelse(is.na(df$col1), df$col1, ifelse(df$col1 %in% ("eat") | df$col2 %in% ("yes"), 1, 0))
df
#> col1 col2 newcolumn
#> 1 <NA> yes <NA>
#> 2 drink yes 1
#> 3 drink no 0
#> 4 drink no 0
#> 5 eat yes 1
#> 6 eat yes 1
#> 7 eat yes 1
#> 8 <NA> yes <NA>
#> 9 eat no 1
#> 10 drink yes 1