Reputation: 91
I am trying to write my first function using rlang
and I am having some trouble fixing the following error.
I've read the vignette, but didn't see a good example of what I'm trying to do.
library(babynames)
library(tidyverse)
name_graph <- function(data, name, sex){
name <- enquo(name)
sex <- enquo(sex)
data %>%
filter_(name == !!name, sex == !!sex) %>%
select(year, prop) %>%
ggplot()+
geom_line(mapping = aes(year, prop))
}
name_graph(babynames, Robert, M)
I'm expecting my distribution graph, but getting an error:
Called from: abort(paste_line("Quosures can only be unquoted within a quasiquotation context.", "", " # Bad:", " list(!!myquosure)", "", " # Good:", " dplyr::mutate(data, !!myquosure)"))
Upvotes: 4
Views: 3943
Reputation: 886928
We can modify the function by converting the quosures (enquo
) to string in the filter
library(rlang)
library(dplyr)
library(ggplot2)
name_graph <- function(data, name, sex){
name <- enquo(name)
sex <- enquo(sex)
data %>%
filter(name == !! as_label(name), sex == !! as_label(sex)) %>%
select(year, prop) %>%
ggplot()+
geom_line(mapping = aes(year, prop))
}
name_graph(babynames, Robert, M)
Upvotes: 8
Reputation: 11981
the function filter_
is deprecated and you should try avoid using it.
Also dplyr::filter
doesn't work well if the variable name is the same as the input.
Try this:
name_graph <- function(data, myname, mysex){
data %>%
filter(name == myname, sex == mysex) %>%
select(year, prop) %>%
ggplot()+
geom_line(mapping = aes(year, prop))
}
Also, as mentioned in the comments, quosures are used if you try passing column names as input arguments. In your case you are passing character strings as inputs so you do not need quosures and it's better not to use them in your case.
Upvotes: 3