How can I use one column's value (eg, x
below) to select among values among possible columns, when the selection is specific to each row?
The x
variable determines whether variable a
, b
, or c
should be selected for a given row. Here's a simplified example; the real cells aren't a concatenation of the column name and row number.
library(magrittr); requireNamespace("tibble"); requireNamespace("dplyr")
ds <- tibble::tibble(
x = c( 1 , 1 , 2 , 3 , 1 ),
a = c("a1", "a2", "a3", "a4", "a5"),
b = c("b1", "b2", "b3", "b4", "b5"),
c = c("c1", "c2", "c3", "c4", "c5")
)
The desired columns are values are:
# ds$y_desired <- c("a1", "a2", "b3", "c4", "a5")
# ds$column_desired <- c("a" , "a" , "b" , "c" , "a" )
Of course the following doesn't produce a single column, but fives columns.
ds[, ds$column_desired]
And the following produces the error:
Error in mutate_impl(.data, dots) : basic_string::_M_replace_aux
.
ds %>%
dplyr::rowwise() %>%
dplyr::mutate(
y = .[[column_desired]]
) %>%
dplyr::ungroup()
If my real scenario had only two or three choices, I'd probably use nested-ifs, but I'd like a generalized mapping approach to accommodate a larger number of conditions.
ds %>%
dplyr::mutate(
y_if_chain = ifelse(x==1, a, ifelse(x==2, b, c))
)
Ideally the approach could be directed by a lookup table, or some other metadata object like:
ds_lookup <- tibble::tribble(
~x, ~desired_column,
1L, "a",
2L, "b",
3L, "c"
)
I'm sure this column switching question has been asked before, but I didn't find one that applied.
I'd prefer a tidyverse solution (b/c that's what my team is most comfortable with), but I'm open to any tool. I couldn't figure out how to use a combination of apply and kimisc::vswitch.
Try this: