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))
}
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.