2017-01-10 12 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. から名前を抽出するために、あなたは、従来のdplyr関数に変数に保存されているカラム名を渡すことはできませんas.name

    a<-"Col_Name"

    as.name(a) = Col_Name

  2. を使用する必要があります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

は、これらの変異体を使用してみてください使用する必要があります。 質問がある場合はお知らせください。