How to pass name of column stored as character in the different column to the mutate
expression, so that expression can use different column for every row?
df <- data.frame(which_col = c("A", "A", "B", "B"),
A = c(1, 2, 3, 4),
B = c(100, 200, 300, 400),
C = c(10, 10, 10, 10),
stringsAsFactors = F)
output <- df %>%
dplyr::mutate(result = which_col * C) # of course this doesn't work
expected_output <- data.frame(which_col = c("A", "A", "B", "B"),
A = c(1, 2, 3, 4),
B = c(100, 200, 300, 400),
C = c(10, 10, 10, 10),
result = c(10, 20, 3000, 4000),
stringsAsFactors = F)
So if which_col == "A"
expression is result = A * C
, while for which_col == "B"
expression is result = B * C
I know that case_when
might be the option, but in case of many possible columns and if expression is more complicated, this would create many duplicates.