4

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)"))

Cettt
  • 11,460
  • 7
  • 35
  • 58
H5470
  • 91
  • 1
  • 8

2 Answers2

8

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)

enter image description here

akrun
  • 874,273
  • 37
  • 540
  • 662
3

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.

Cettt
  • 11,460
  • 7
  • 35
  • 58
  • 2
    You should point out that they don't seem to need quosures here, since they're not passing in a variable name – divibisan Mar 28 '19 at 20:49
  • @Cettt `Error in ~name == myname : object 'Chris' not found Called from: ~name == myname attr(,"class") [1] "quosure" "formula" attr(,".Environment") ` That's what I got with your code. – H5470 Mar 29 '19 at 13:05
  • 1
    you have to call the function like this: `name_graph(babynames, "Robert", "M")` – Cettt Mar 29 '19 at 13:11