mutate expression - how to pass name of column stored as character in the different column?

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.

I have a work-up on the related question of using one column to pick from other columns (inspired by an earlier RStudio community question): here.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.