我怎么能在类似问题的函数传递一个列名在这里,但使用dplyr
链接和filter()
一起%in%
。
require(dplyr)
set.seed(8)
df <- data.frame(
A=sample(c(1:3), 10, replace=T),
B=sample(c(1:3), 10, replace=T))
如果要获取列A为1或2的行,我可以这样做:
df %>% filter(A %in% c(1,2))
我得到:
A B
1 2 3
2 1 2
3 1 3
4 2 1
5 1 1
6 1 3
现在,我如何将其放入一个可以指定列的函数中,这将不起作用:
fun1 <- function(x, column, n){
res <-
x %>% filter(column %in% n)
return(res)
}
fun1(df, A, c(1,2))
你可以试试
fun1 <- function(x, column, n){
x %>%
filter_(lazyeval::interp(quote(x %in% y), x=as.name(column), y=n))
}
fun1(df, 'A', 1:2)
或者
fun2 <- function(x, column, n){
args <- as.list(match.call())
x %>%
filter(eval(args$column, x) %in% n)
}
fun2(df, A, 1:2)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句