use a variable instead of variable name with dplyr

Wilcar

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)) 
user13653858

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)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related