I often run into the problem of having to recode multiple columns that follow the same structure and saving them into a column with a different name. If I could overwrite them, this would just be one line in dplyr, but since I also want to keep the original column, I don't know a good solution. Below an illustration.
This would be the long code the output of which I would like to replicate:
library(dplyr)
library(ggplot2)
data("diamonds")
diamonds <- diamonds %>%
mutate(x_char = case_when(x <= 4.5 ~ "low",
x > 4.5 & x < 7 ~ "so-so",
x >= 7 ~ "large",
TRUE ~ as.character(NA)),
y_char = case_when(y <= 4.5 ~ "low",
y > 4.5 & y < 7 ~ "so-so",
y >= 7 ~ "large",
TRUE ~ as.character(NA)),
z_char = case_when(z <= 4.5 ~ "low",
z > 4.5 & z < 7 ~ "so-so",
z >= 7 ~ "large",
TRUE ~ as.character(NA)))
This would be the short code with mutate_at that overwrites the original columns:
library(dplyr)
library(ggplot2)
data("diamonds")
diamonds <- diamonds %>%
mutate_at(vars(x, y, z), ~ case_when(. <= 4.5 ~ "low",
. > 4.5 & . < 7 ~ "so-so",
. >= 7 ~ "large",
TRUE ~ as.character(NA)))
Is there a way to keep the short code with mutate_at but change it in a way that the original columns are kept, and the new ones are saved with a different name? In the example that would mean adding _char at the end of the original column name and changing the recode according to the embedded formula.