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

狂风中的少年 提交于 2019-12-08 02:58:11

问题


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


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/55406546/how-to-fix-quosures-can-only-be-unquoted-within-a-quasiquotation-context-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!