I’m generating multiple columns in a mutate()
call, all by using a function of 1) an already-existing column and 2) some value which is different for each output column. The following code produces what I want, but it smells:
df <- tibble(base_string = c("a", "b", "c"))
df_desired_result <- df |>
mutate(
one = str_c(base_string, "1"),
two = str_c(base_string, "2"),
three = str_c(base_string, "3")
)
If there were many other columns, this would be a bad solution.
The best improvement I’ve come up with is:
df_also_desired_result <- df |>
expand_grid(
tibble(
number_name = c("one", "two", "three"),
number_string = c("1", "2", "3")
)
) |>
mutate(final_string = str_c(base_string, number_string)) |>
pivot_wider(
id_cols = base_string,
names_from = number_name,
values_from = final_string
)
But this seems too verbose. Would love any suggestions on a nicer way to do this.
New contributor
eithompson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.