Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Column from String in dplyr [duplicate]

Tags:

r

dplyr

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?

like image 356
Georgery Avatar asked Oct 14 '25 02:10

Georgery


1 Answers

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
like image 199
A. Suliman Avatar answered Oct 16 '25 17:10

A. Suliman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!