Hi all, Below is the simple filtering that is done on Iris data set
iris_new <- iris %>% filter(Species == "setosa")
But I am trying to create a function where the functions takes data, category as input and then filters. Example
## df is a dataframe, cat is column on which filtering is applied and cat_val is the categorical values
filter_fun <- function(df, cat, cat_val){
res <- df %>% filter(cat == "cat_val")
return(res)
}
So when I try running below, I get error. Appreciate if anyone could help me whtat wrong I am doing here
I think that there are two problems with the code, one that is explicit, which is the one that you are getting, and one implicit. In the code that you have:
You get the following error: object 'Species' not found. That's because Species doesn't come on its own, it comes from the iris dataset, so you should have:
filter_fun(iris, iris$Species, "setosa")
But that won't work either, not in the sense that you would get an error, but it won't do what you want. That's because in your function you have cat == "cat_val", so the filter will try to match to specifically "cat_val", so you should change it to cat = cat_val for it to work correctly.
Thanks. I tried below as you mentioned but still got error
filter_fun <- function(df, cat, cat_val){
res <- df %>% filter(cat = cat_val)
return(res)
}
filter_fun(iris, iris$Species, "setosa")
Error: Problem with `filter()` input `..1`.
x Input `..1` is named.
ℹ This usually means that you've used `=` instead of `==`.
ℹ Did you mean `cat == cat_val`?
Run `rlang::last_error()` to see where the error occurred.