2017-01-10 213 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

嘗試使用這些變體。 如果您有任何疑問,請告訴我。