3

我想 在我的函数内部使用filterand summarisedplyr如果没有函数,它的工作方式如下:

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 
4

1 回答 1

4

提供字符参数并使用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
于 2017-01-23T16:24:25.763 回答