2017-01-23 23 views
2

我想在我的函數中使用dplyr中的filtersummarise。沒有它,就像下面的功能:如何在r中的函數定義中正確使用dplyr動詞?

library(dplyr) 
> Orange %>% 
+  filter(Tree==1) %>% 
+  summarise(age_max = max(age)) 
    age_max 
1 1582 

我想做一個函數中的一樣,但以下失敗:

## Function definition: 

df.maker <- function(df, plant, Age){ 

    require(dplyr) 

    dfo <- df %>% 
    filter(plant==1) %>% 
    summarise(age_max = max(Age)) 

    return(dfo) 
} 

## Use: 
> df.maker(Orange, Tree, age) 

Rerun with Debug 
Error in as.lazy_dots(list(...)) : object 'Tree' not found 

我知道,類似的問題已經被問過。我也經歷了一些相關的鏈接,如page1page2。但是我不能完全理解NSE和SE的概念。我試過如下:

df.maker <- function(df, plant, Age){ 

    require(dplyr) 

    dfo <- df %>% 
    filter_(plant==1) %>% 
    summarise_(age_max = ~max(Age)) 

    return(dfo) 
} 

但是得到同樣的錯誤。請幫助我瞭解發生了什麼事。我怎樣才能正確地創建我的功能?謝謝!

編輯:
我也嘗試以下操作:

df.maker <- function(df, plant, Age){ 

    require(dplyr) 

    dfo <- df %>% 
    #filter_(plant==1) %>% 
    summarise_(age_max = lazyeval::interp(~max(x), 
              x = as.name(Age))) 

    return(dfo) 
} 

> df.maker(Orange, Tree, age) 
Error in as.name(Age) : object 'age' not found 
+1

不[此](http://stackoverflow.com/questions/40017629/using-dplyr-within-a-function-non-standard-evaluation/40018601#40018601)回答你的問題? – Axeman

+0

@Axeman,我試過了,如我的編輯所示。但它仍然不起作用。我認爲這與環境有關。 –

回答

2

任一電源字符的參數和使用as.name

df.maker1 <- function(d, plant, Age){ 
    require(dplyr) 
    dfo <- d %>% 
    filter_(lazyeval::interp(~x == 1, x = as.name(plant))) %>% 
    summarise_(age_max = lazyeval::interp(~max(x), x = as.name(Age))) 
    return(dfo) 
} 
df.maker1(Orange, 'Tree', 'age') 
age_max 
1 1582 

或捕捉與substitute參數:

df.maker2 <- function(d, plant, Age){ 
    require(dplyr) 
    plant <- substitute(plant) 
    Age <- substitute(Age) 

    dfo <- d %>% 
    filter_(lazyeval::interp(~x == 1, x = plant)) %>% 
    summarise_(age_max = lazyeval::interp(~max(x), x = Age)) 
    return(dfo) 
} 
df.maker2(Orange, Tree, age) 
age_max 
1 1582 
+1

非常感謝!我不知道'substitute()'。 –

相關問題