Using the dplyr () filter in programming

I am writing my own function and want to use the dplyr filter () function to select the rows of my data frame that satisfy the 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() 

At any time, when I run this function, it looks like filter not selecting rows that satisfy the condition.

How can I do this job?

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 for each cycle are the same. Why is this so? and why I can not use %in% .

+5
source share
2 answers

This is similar to what you want (but it needs confirmation):

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

Although there are many “official” examples of “tidyverse” using df , this is a function in stats pkg, and I try not to use it anymore.

Since you are using tidyverse, you can also use map_df() from purrr .

+7
source

I agree with the standard solution for evaluating @hrbrmstr. As @hadley suggested today , the NSE solution here:

 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){ ang <- enquo(ang) brad <- enquo(brad) drau <- enquo(drau) df %>% filter(UQ(drau) %in% 1:50) %>% select(UQ(ang),UQ(brad)) } brand <- c("z","w","p") brand <- rlang::syms(brand) map_df(brand, ~new(ang = x, brad = y, drau = UQ(.x))) 
+8
source

Source: https://habr.com/ru/post/1270040/


All Articles