Variable quote within function

I want to compute the mean of some variables using function. But the function I created did not work since it returned the warning "Unknown or uninitialised column: y.".

For the simple code, sub[sub$country == 'Germany',]$"ff_mean" works well, but test('ff') fails. I guess it is a problem on the variable quote within function, could you please let me know how I can solve this? Thanks!

Function:

test <- function(var) {
  
  y <<- str_interp('${var}_mean') 
  mean_G <<- sub[sub$country == 'Germany',]$y 
}

I also tried this, but still failed - Error: attempt to apply non-function

test <- function(var) {
  
  y <<- str_interp('${var}_mean') 
  mean_G <<- sub[sub$country == 'Germany',]$eval(quote(y))
}

In general, this simplest function did not work. Does anyone know how I can solve this? Thanks!


test <- function(df, var) {
  
  mean_G <<- df$var  

}

return_var_from_df <- function(df, var) {
df[[var]]
}

return_var_from_df(df=head(iris),
                   var="Sepal.Length")

#first way only handles strings ...
return_var_from_df(df=head(iris),
                   var=Sepal.Length)

#more general can use symbols 
return_var_from_df <- function(df, var) {

  df[[substitute(var)]]
}

return_var_from_df(df=head(iris),
                   var="Sepal.Length")

return_var_from_df(df=head(iris),
                   var=Sepal.Length)

recommend you avoid using functions to assign values to global scope in their internals, its a very good idea to return from the function and rely on code that calls the function to assign it to an object name, or otherwise.

I agree with @ nirgrahamuk. The function should accept arguments and return an argument. It shouldn't modify variables outside the function.

This might be useful:

library(tidyverse)
head(iris)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          5.1         3.5          1.4         0.2  setosa
#> 2          4.9         3.0          1.4         0.2  setosa
#> 3          4.7         3.2          1.3         0.2  setosa
#> 4          4.6         3.1          1.5         0.2  setosa
#> 5          5.0         3.6          1.4         0.2  setosa
#> 6          5.4         3.9          1.7         0.4  setosa
iris %>% summarize_if(is.numeric, mean, na.rm = TRUE)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width
#> 1     5.843333    3.057333        3.758    1.199333

Created on 2021-06-25 by the reprex package (v1.0.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.