How can I pass a column name in a function similar to the question here but using dplyr
chaining and filter()
together with %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))
If want to get rows where column A is 1 or 2 I can do:
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
Now, how can I put this in a function, where one can specify the column, this does not work:
fun1 <- function(x, column, n){
res <-
x %>% filter(column %in% n)
return(res)
}
fun1(df, A, c(1,2))