在编程中使用dplyr filter() [英] Using dplyr filter() in programming
问题描述
我正在编写函数,并希望使用dplyr的filter()函数来选择数据框中满足条件的行。这是我的代码:
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.
如何进行这项工作?
更新
出于某些原因,当我不使用时,此方法有效`%in%,如;
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()
但是,每个循环的结果都相同。为什么会这样呢?以及为什么我不能使用%in%
。
However, the results are the same for every loop. Why is this so? and also why can't I use %in%
.
推荐答案
这似乎可以满足您的要求(但需要您的确认):
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))
尽管有很多使用<$的官方 tidyverse示例c $ c> df ,这是 stats
pkg中的函数,我尝试避免再使用它。
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.
由于您使用的是tidyverse,因此不妨利用<$ c $中的 map_df()
c> purrr 。
Since you're using the tidyverse, might as well take advantage of map_df()
from purrr
.
这篇关于在编程中使用dplyr filter()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!