Search code examples
rdplyrtidyverserlang

Using dplyr filter() in programming


I am writing my function and want to use dplyr's filter() function to select rows of my data frame that satisfy a condition. This is my code:

library(tidyverse)

df <-data.frame(x = sample(1:100, 50), y = rnorm(50), z = sample(1:100,50), w = sample(1:100, 50),
            p = sample(1:100,50))

new <- function(ang,brad,drau){
  df%>%filter(!!drau %in% 1:50)%>%select(ang,brad) -> A
return(A)
}

brand <- c("z","w","p")
lapply(1:3, function(i) new(ang = "x", brad = "y", drau = brand[i]))%>%bind_rows()

Anytime I run this function, it looks like filter doesn't select any rows that satisfy the condition.

How can I make this work?

Update

For some reason, this works when I don't use `%in%, as in;

new <- function(ang,brad,drau){
  df%>%filter(!!drau > 50)%>%select(ang,brad) -> A
return(A)
}

lapply(1:3, function(i) new(ang = "x", brad = "y", drau = brand[i]))%>%bind_rows()

However, the results are the same for every loop. Why is this so? and also why can't I use %in%.


Solution

  • This appears to do what you want (but it needs confirmation by you):

    library(tidyverse)
    library(rlang)
    
    set.seed(1492)
    
    xdf <- data_frame(
      x = sample(1:100, 50),
      y = rnorm(50), 
      z = sample(1:100,50), 
      w = sample(1:100, 50),
      p = sample(1:100,50)
    )
    
    new_df <- function(ang, brad, drau) {
      drau <- sym(drau)
      filter(xdf, UQE(drau) %in% 1:50) %>% 
        select(ang, brad)
    }
    
    brand <- c("z", "w", "p")
    
    map_df(brand, ~new_df(ang = "x", brad = "y", drau = .x))
    

    Despite there being a plethora of "official" "tidyverse" examples using df, it's a function in the stats pkg and I try to avoid using it anymore.

    Since you're using the tidyverse, might as well take advantage of map_df() from purrr.