如何在类似于问题的函数中传递列名here https://stackoverflow.com/questions/2641653/pass-a-data-frame-column-name-to-a-function但使用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))
I get:
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))