mutate a column via its name in r

To mutate a column via its name in R, you can use the mutate function from the dplyr package.

Assuming you have a data frame called df, and you want to add a new column called new_col based on the values in an existing column called old_col, you can use the mutate function as follows:

main.r
library(dplyr)

df <- df %>%
  mutate(new_col = old_col * 2)
61 chars
5 lines

This will create a new column called new_col in df, which will contain the values of old_col multiplied by 2.

If you know the name of the column you want to mutate, but you don't want to hardcode the column name in your code, you can use string interpolation to dynamically construct the column name. For example:

main.r
col_name <- "old_col"

df <- df %>%
  mutate(new_col = !!sym(col_name) * 2)
76 chars
5 lines

This will achieve the same result as the previous example, but will use the value of the col_name variable as the column to mutate. The !! operator is used to unquote an expression and evaluate it as code. sym() is used to create a symbol from a string. Together, they allow us to interpolate the column name into the dplyr chain.

gistlibby LogSnag