How to fix 'Quosures can only be unquoted with

2019-08-03 08:05发布

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

2条回答
孤傲高冷的网名
2楼-- · 2019-08-03 08:41

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

查看更多
家丑人穷心不美
3楼-- · 2019-08-03 08:50

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.

查看更多
登录 后发表回答