2017-01-10 91 views
0

我的代码类似如下:功能参数

output <- iris %>% 
    select(Sepal.Length, Sepal.Width, Species) %>% 
    filter(Sepal.Width < 3) %>% 
    group_by(Species) %>% 
    summarise(mean(Sepal.Length)) %>% 
    print 
# works as expected 

# But when I want to write a function like this: 
output_function <- function(a, b, c) { 
    out <- iris %>% 
    select(a, b, c) %>% 
    filter(b < 3) %>% 
    group_by(c) %>% 
    summarise(mean(a)) 
    return(out) 
} 

output_function(Sepal.Length, Sepal.Width, Species) 
# does not work as expected 

原因是显而易见的,但我不知道如何解决它。
当我们使用select,group_by等函数时,我不知道列变量的变量类型。
因此,我不知道如何在这种情况下定义正确的参数,以便它们可以传递给函数在dplyr。

+4

查看dplyr非标准评估的许多帖子和小插图:https://cran.r-project.org/web/packages/dplyr/vignettes/nse.html – alistaire

+3

您需要做这样的事情 - http://stackoverflow.com/questions/27975124/pass-arguments-to-dplyr-functions – thelatemail

回答

1
  1. 从存储在一个字符串变量中提取的名字,你将不得不使用as.name

    a<-"Col_Name"

    as.name(a) = Col_Name

  2. 您不能通过存储在一个变量常规dplyr功能列名如select(),group_by()。你将不得不使用select_()group_by_()代替

    a<- "Sepal.Length"

    select(iris, as.name(a)) #this will NOT work

    select_(iris, as.name(a)) #this will work

尝试使用这些变体。 如果您有任何疑问,请告诉我。