Use I string to refer to a variable inside dplyr?

Ignacio

Suppose I have the following data:

test_df <- data.frame(a=rnorm(100), b=rnorm(100))

The following works:

test_df %>% 
  summarise(y = mean(a))

Now suppose that instead of a i want to pass a character string

string_outcome <- "a" # I want to use this

test_df %>% 
  summarise(y = mean(string_outcome))

That won't work. I tried using !!string_outcome but that does not work either. How can I fix this?

akrun

As it is a string, convert it to symbol (sym from rlang) and evaluate (!!)

test_df %>%
     summarise(y = mean(!! rlang::sym(string_outcome)))

Or use summarise_at which can take strings in vars parameter

test_df %>%
    summarise_at(vars(string_outcome), list(y = ~  mean(.)))

Or if we need a single value without any attributes, even pull with mean can be used

test_df %>% 
       pull(string_outcome) %>%
       mean

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I put a variable inside a string?

Javascript - Use variable inside push string

Why it says that "Cannot refer to a non-final variable i inside an inner class defined in a different method"?

I want to refer to a non-final variable inside an inner class defined in a different method

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

Can I use a variable inside of an input statement?

C# How do I use a variable outside of a loop that changes from string to int inside the loop?

How to refer to variable instead of column with dplyr

use string vector elements to refer to variable names in r

Use variable inside Invoke-Expression string

passing variable to dplyr as string

how to use string variable as filter condition in dplyr

how can I use mutate in dplyr to modify variable dynamically?

Use PHP Variable inside PHP string

R dplyr: how to use ... with summarize(across()) when ... will refer to a variable name within the data?

variable use in dplyr and ggplot

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

How can i use dynamically generated string inside `list() = $variable`?

How can I use a string variable that contains square brackets inside a regex pattern?

How can I use a for loop to modify a variable inside a string while I download a list of images using BS?

How can I use a pre-assigned variable in dplyr::filter?

How to use string manipulation functions inside .names argument in dplyr::across

I cant use a variable inside an if statement in jinja

refer to column name from variable in across in dplyr

Generate Variable Inside Loop Dplyr

Turn variable name into string inside function dplyr

Why can I refer to a variable inside (( )) without the $ symbol?

Is it possible to use dynamic variable inside dplyr::starts_with?

Merge in dplyr by a string variable