I am trying to use mutate
to create a new column with values based on a specific column.
Example final data frame (I am trying to create new_col
):
x = tibble(colA = c(11, 12, 13),
colB = c(91, 92, 93),
col_to_use = c("colA", "colA", "colB"),
new_col = c(11, 12, 93))
I would like to do something like:
x %>% mutate(new_col = col_to_use)
Except instead of column contents, I would like to transform them to a variable. I started with:
col_name = "colA"
x %>% mutate(new_col = !!as.name(col_name))
That works with a static variable. However, I have been unable to change the variable to represent the column. How do I take a column name based on contents of a different column?
This question is basically the opposite of this: dplyr - mutate: use dynamic variable names. I wasn't able to adapt the solution to my problem.