I am trying to print aggregate tables and plots for different columns but when i pass a column name it is saying 'object is not found'. Here is a simple example:
df <- data.frame(
"age" = c(1,2,3),
"name" = c("a", "b", "c")
)
l <- c("age", "name")
#function to loop through columns
func <- function(df, parameter){
return(
df %>%
count(parameter)
)
}
When I call the above func
like this
func(df, "age")
I am getting this error:
Error in `group_by()`:
! Must group by variables found in `.data`.
✖ Column `parameter` is not found.
What could be the reason? Is it not allowed to pass column name as a string? If not, then how should I proceed? thanks in advance.
CodePudding user response:
You have a typo in your code. paramert
is supposed to be parameter
.
So change count(paramert)
to count(parameter)
CodePudding user response:
You need to turn column name strings into symbols and inject them inside a data-masked expression with !!!
. For more details, see the symbolise-and-inject pattern of metaprogramming in R.
func1 <- function(df, parameter){
return(
df %>%
count(!!!syms(parameter))
)
}
func1(df, "age")
# age n
# 1 1 1
# 2 2 1
# 3 3 1
func1(df, c("age", "name"))
# age name n
# 1 1 a 1
# 2 2 b 1
# 3 3 c 1