use string content of a variable to refer to a column in a dataframe using transmute dplyr

Jonas :

I would like to use the variable "second_column" as a variable to refer to the column "test1$b". I tried different things, but couldn't find any solutions yet. test1 and test2 should be the same in the end...

test1 <- data.frame(a = 1:5, b = 6:10)

second_column = "b"

test2 <- test1 %>% 
  transmute(variable1 = a,
         variable2 = second_column
  )

test1
test2

Duck :

I would suggest using !! from rlang and as.name(). These two elements are useful for the kind of evaluation you want in order to create your variables:

#Data
test1 <- data.frame(a = 1:5, b = 6:10)
#Var name
second_column = "b"
#Data 2
test2 <- test1 %>% 
  transmute(variable1 = a,
            variable2 = !!as.name(second_column)
  )
#Dataframes
test1
test2

Output:

test1

  a  b
1 1  6
2 2  7
3 3  8
4 4  9
5 5 10

test2

  variable1 variable2
1         1         6
2         2         7
3         3         8
4         4         9
5         5        10

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Use I string to refer to a variable inside dplyr?

Is it possible to use scoped variant of transmute and still keep first column in dplyr?

How do we refer to a dataframe column with an interaction term using a string variable?

Creating a function that calls a column both using a string and as a variable - use of base R and dplyr

refer to column name from variable in across in dplyr

How to refer to variable instead of column with dplyr

Replace column values with column name using dplyr's transmute_all

How to use NSE in dplyr to refer to one variable?

r dplyr transmute_ string input error

Conditionally filter rowwise on a dataframe for a column variable with dplyr

Refer to column name using variable in PROC SQL

Evaluate string in column of dataframe with a variable

How to count the number of times a specified variable appears in a dataframe column using dplyr?

DPLYR Mutate function to "transmute"?

Select column from dataframe using dplyr

Include column in first position of a dataframe using dplyr

Add a column in a dataframe with the content of a variable that contains a tapply

dplyr filter values of a dataframe variable using ifelse?

using variable column names in dplyr summarise

How to achieve a large tibble divided by a column within using transmute_if / transmute_at

using a variable to specify a column in a dataframe

how to use string variable as filter condition in dplyr

Recode a string column into integer using dplyr

How to add a column into a tibble using tq_transmute()?

Dplyr rename using string variable as expression

R dplyr:: rename and select using string variable

R loop over string and use it to refer to column names

Use content of binary as string in DataFrame in pyspark

R dplyr: Use the function as a string in one column on the next column