Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

dplyr

ggplot2

nse

I have a function that I'm trying to create using filter !=, but it doesn't work. I wonder if it is due to something related with tidy evaluation.

This is what I tried:

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)

This is the function I tried to write:

    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)

What I am trying to achieve is to remove "Neither" values and I tried this using filter(!var == "Neither") but that doesn't work and I'm still getting "Neither" plotted. And I also lost the title of the chart.

enter image description here

This is what I'm trying to achieve:

enter image description here

I was able to do this with a few lines of code:

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

But I'm not able to figure out how to convert it into a function.

like image 604
writer_typer Avatar asked Dec 05 '25 06:12

writer_typer


1 Answers

enter image description here

Try eval as 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)
like image 141
Liman Avatar answered Dec 07 '25 20:12

Liman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!