1

I have a df :

v1 <- c(100, 20, 5, 30)
v2 <- c(10, 13, 2, 30)
v3 <- c(10, 200, 5, 300)
df <- data.frame(v1, v2, v3)


  v1 v2  v3
  1 100 10  10
  2  20 13 200
  3   5  2   5
  4  30 30 300

I don't want to use a column name directly with dplyr but refer to a column name stored in a variable (o that I can change it easily throughout a program. This variable is called column_used. in my example, column_used is v1.

column_used <- "v1"

I want to use this variable mut it is not working :

df %>%
mutate(taux = (column_used/ 100)) 
Wilcar
  • 2,349
  • 2
  • 21
  • 48

2 Answers2

4

Using dplyr, here are two options :

library(dplyr)
df %>% mutate(taux = !!sym(column_used)/ 100)

Or

df %>% mutate(taux = .data[[column_used]]/100)

#   v1 v2  v3 taux
#1 100 10  10 1.00
#2  20 13 200 0.20
#3   5  2   5 0.05
#4  30 30 300 0.30

In base R, you can do :

df$taux <- df[[column_used]]/100
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
4

column_used is only a string and you need to convert it to symbol (i.e. to say that it's not a string, but it's a variable/column name).

You can achieve this e.g. by using get() from base or as.name() or sym() with !! operator from rlang:

# get()
df %>%
    mutate(taux = get(column_used) / 100)

# !!as.name()
df %>%
    mutate(taux = !!as.name(column_used) / 100)

# !!sym()
df %>%
    mutate(taux = !!sym(column_used) / 100)