如何使用 "not equal to" 创建一个函数?

How to create a function with "not equal to"?

我尝试使用 filter != 创建一个函数,但它不起作用。不知道是不是和tidy evaluation有关的问题

这是我试过的:

library(haven)
library(dplyr)
library(labelled)
library(sjlabelled)

data <- read_spss("http://staff.bath.ac.uk/pssiw/stats2/SAQ.sav")
data$Q01_L <- as_label(data$Q01)

这是我尝试编写的函数:

    bar_plot <- function(data, var) {
      var <- rlang::ensym(var)
      
      data %>% 
        filter(!var == "Neither") %>% 
        ggplot(aes(!!var)) +
        geom_bar() +
        coord_flip() +
        theme_classic() +
        labs(x = "Question", y = "Count", title = var_label(data$var)) 
    }
    
    
    bar_plot(data, Q01_L)

我想要实现的是删除“两者都不”值,我尝试使用 filter(!var == "Neither") 进行此操作,但这不起作用,我仍然绘制“两者都不”。而且图表的标题我也丢了。

这就是我要实现的目标:

我可以用几行代码做到这一点:

data %>% 
  filter(!Q01_L == "Neither") %>% 
  ggplot(aes(Q01_L)) +
  geom_bar() +
  coord_flip() +
  theme_classic() +
  labs(x = "Question", y = "Count", title = var_label(data$Q01_L)) 

但我不知道如何将其转换为函数。

尝试 eval 作为 filter(!eval(var) == "Neither")

 bar_plot <- function(.data, var) {
    var <- rlang::ensym(var)
    
    data %>% 
        filter(!eval(var) == "Neither") %>% 
        ggplot(aes(!!var)) +
        geom_bar() +
        coord_flip() +
        theme_classic() +
        labs(x = "Question", y = "Count", title = var_label(data[var])) 
}


bar_plot(data, Q01_L)

您还可以使用 !!(感谢@DarrenTsai)和 !=:

#Plot
bar_plot <- function(.data, var) {
  var <- rlang::ensym(var)
  
  data %>% 
    filter(!!var != "Neither") %>% 
    ggplot(aes(!!var)) +
    geom_bar() +
    coord_flip() +
    theme_classic() +
    labs(x = "Question", y = "Count", title = var_label(data[,var])) 
}


bar_plot(data, Q01_L)

输出:

您可以在函数中使用curly-curly运算符,这样就可以删除var <- rlang::ensym(var)

来自help("nse-force")

The curly-curly operator {{ }} for function arguments is a bit special because it forces the function argument and immediately defuses it. The defused expression is substituted in place, ready to be evaluated in another context, such as the data frame.

bar_plot <- function(data, var) {
  
  data %>% 
    filter({{var}} != "Neither") %>% 
    ggplot(aes( {{var}} )) +
    geom_bar() +
    coord_flip() +
    theme_classic() +
    labs(x = "Question", y = "Count", title = var_label(pull(data, {{var}})))
}

bar_plot(data, Q01_L)