Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix 'Quosures can only be unquoted within a quasiquotation context' error in R function

Tags:

r

rlang

tidyverse

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

like image 383
H5470 Avatar asked Dec 17 '22 17:12

H5470


2 Answers

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

like image 53
akrun Avatar answered Jan 13 '23 13:01

akrun


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.

like image 29
Cettt Avatar answered Jan 13 '23 15:01

Cettt