簡體   English   中英

R,使用dplyr :: filter()和%in%將列名作為參數傳遞給函數

[英]R, pass column name as argument to function using dplyr::filter() and %in%

如何在類似於此處問題的函數中傳遞列名,但使用dplyr chaining和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)

如果您想保留您的功能,請嘗試:

fun1 <- function(x, column, n){
  res <- x %>% filter_(paste(column,"%in%",n))
  return(res)
}

fun1(df, "A", "c(1,2)")

嘗試將您的功能更改為

fun1 <- function(x, column, n){
    require(lazyeval)
    filter_(x,
        interp(quote(col %in% n),
            col = lazy(column), n = n))
}

all(fun1(df, A, c(1, 2)) == filter(df, A %in% c(1,2)))
# TRUE

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM