I'm learning R and looking for best practices here...
Main question
Given the tibble my_tibble:
# A tibble: 5 x 3
chkA chkB chkC
<chr> <chr> <chr>
1 NA NA NA
2 x NA NA
3 NA x NA
4 x NA NA
5 NA NA x
I want to create a variable/column checked that specifies which of the variables chkA, chkB or chkC that equals "x". For each observation/row, only zero or one of those three variables can equal "x", while the rest of them are NA.
I can solve it with this code:
my_tibble <- my_tibble %>% mutate(checked = case_when(
chkA == "x" ~ "A",
chkB == "x" ~ "B",
chkC == "x" ~ "C",
TRUE ~ "(none)"
))
, which produces this tibble:
# A tibble: 5 x 4
chkA chkB chkC checked
<chr> <chr> <chr> <chr>
1 NA NA NA (none)
2 x NA NA A
3 NA x NA B
4 x NA NA A
5 NA NA x C
However, I assume/hope there could be a more convenient/elegant solution, perhaps a one-liner or something, as I think this is a frequent problem.
Bonus/follow-up question
For a "cleaner" tibble, I'd probably like to get rid of the chr variables and their NAs, by converting to lgl variables. I solved that with this code:
my_tibble <- my_tibble %>% mutate(chkA = ifelse(is.na(chkA), FALSE, TRUE))
my_tibble <- my_tibble %>% mutate(chkB = ifelse(is.na(chkB), FALSE, TRUE))
my_tibble <- my_tibble %>% mutate(chkC = ifelse(is.na(chkC), FALSE, TRUE))
, creating this tibble:
# A tibble: 5 x 3
chkA chkB chkC
<lgl> <lgl> <lgl>
1 FALSE FALSE FALSE
2 TRUE FALSE FALSE
3 FALSE TRUE FALSE
4 TRUE FALSE FALSE
5 FALSE FALSE TRUE
Is there a better way?