This problem is hard to express in a title line, but it is a different question than the usual "how do I change the value in one column based on a value in another column." There are two wrinkles I haven't seen dealt with elsewhere: 1) I'm dealing with NAs, not values, 2) I'm dealing with a condition involving an OR relationship between multiple columns, i.e., if V01 is NA or V02 is NA, then make var foo (which already exists with no NAs) NA for that row.
Here's a small tibble to illustrate:
tbl <- tibble(
V01 = 10:15,
V02 = 1:6,
V03 = V02 * 2,
foo = V03 * 2
)
# sprinkle around some NAs
tbl[1,2] = NA
tbl[4,1] = NA
tbl[4,2] = NA
tbl[6,1:3] = NA
that produces this table:
# A tibble: 6 x 4
V01 V02 V03 foo
<int> <int> <dbl> <dbl>
1 10 NA 2 4
2 11 2 4 8
3 12 3 6 12
4 NA NA 8 16
5 14 5 10 20
6 NA NA NA 24
Ultimately I want to produce this kind of logic for each row in tbl:
if (V01 == NA | V02 == NA | V03 == NA) {foo = NA}
I started by trying to use mutateto change foo to NA based on one column, like this:
tbl <- tbl %>%
mutate(
foo = case_when(V01 == NA ~ NA)
)
But even in this simple case, mutate changed every value of foo to NA:
# A tibble: 6 x 4
V01 V02 V03 foo
<int> <int> <dbl> <lgl>
1 10 NA 2 NA
2 11 2 4 NA
3 12 3 6 NA
4 NA NA 8 NA
5 14 5 10 NA
6 NA NA NA NA
I thought maybe I needed a rowwise in there, but that didn't change the result.
Then I thought maybe it's because NAs are weird, so let's try something simpler: change foo to -1 if V01 is NA:
tbl <- tbl %>%
mutate(
foo = case_when(V01 == NA ~ -1)
)
But that produced the same result, all values of foo changed to NA (and the value of foo in row 4 did not change to -1 either).
Then I decided to do something even simpler. Leave the NAs out of the picture. If V01 is 10 (as in the first row only), change the foo value in that row to -1. So:
tbl <- tbl %>%
mutate(
foo = case_when(V01 == 10 ~ -1)
)
And that produced this:
# A tibble: 6 x 4
V01 V02 V03 foo
<int> <int> <dbl> <dbl>
1 10 NA 2 -1
2 11 2 4 NA
3 12 3 6 NA
4 NA NA 8 NA
5 14 5 10 NA
6 NA NA NA NA
So why is mutate changing values in rows that don't meet the specified condition in the mutate statement?
Note I haven't even gotten to the OR condition yet. For what it's worth, this is the result I want to get:
# A tibble: 6 x 4
V01 V02 V03 foo
<int> <int> <dbl> <dbl>
1 10 NA 2 NA
2 11 2 4 8
3 12 3 6 12
4 NA NA 8 NA
5 14 5 10 20
6 NA NA NA NA
I wasn't able to use the dplyr na_if function because it only takes a value to replace with NA, not a condition.
Any guidance would be appreciated. Thanks!