I have a dataframe:
library(tidyverse)
df <- tribble(~col1, ~col2, 1, 2)
Now I want to create a column. I have the name of the new column in a string. It does work like this:
df %>%
mutate("col3" = 3)
# A tibble: 1 x 3
col1 col2 col3
<dbl> <dbl> <dbl>
1 1 2 3
But it does not work like this:
newColumnName <- "col3"
df %>%
mutate(newColumnName = 3)
# A tibble: 1 x 3
col1 col2 newColumnName
<dbl> <dbl> <dbl>
1 1 2 3
How do I create a new column that gets its name from a string in an object?
Use !!
with the definition operator :=
as mentioned here, to set a variable name as the column name.
:= supports unquoting on both the LHS and the RHS
library(dplyr)
newColumnName <- "col3"
df %>% mutate(!!newColumnName := 3)
# A tibble: 1 x 3
col1 col2 col3
<dbl> <dbl> <dbl>
1 1 2 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With