2017-10-29 21 views
5

を使用してギャザーを持つオペレータ:- そのように、私は、引数としてquosureを取るquosureに<code>-</code>を付加し、<code>gather</code>にあることを渡す関数を書きたいのですが非標準の評価

library(tidyverse) 
my_gather <- function(d, not.columns) { 
    dg <- tidyr::gather(d, key = k, value = v, .dots = -!!!not.columns) 
    dg 
} 

de <- my_gather(mtcars, not.columns = quos(mpg, cyl, disp)) 

> Error in `-`(~mpg, ~cyl, ~disp) : operator needs one or two arguments 

この閉鎖全体に-を追加するのではなく、閉鎖の各要素を-に追加する必要があるからです。しかし私の仕事では、quos(-mpg, -cyl, -disp)の形でこの閉鎖を作成するのは簡単ではないでしょう。quos(mpg, cyl, disp)を変更して-を追加するにはどうすればよいですか?

私はgather(mtcars, key = k, value = v, -mpg, -cyl, -disp)と同じである結果を見てみたい、の最初の3行は

mpg cyl disp k v 
1 21.0 6 160 hp 110 
2 21.0 6 160 hp 110 
3 22.8 4 108 hp 93 

ありあり同様の質問hereだが、それは未回答で、対処していないようですquo()ではなくquos()の問題です。

+0

ができますあなたは結果としてあなたが見たいものをより詳細に記述します この? –

+0

@ 42-:編集を参照してください。 –

答えて

3

我々は機能せず

my_gather <- function(d, not.columns) { 
    tidyr::gather(d, key = k, value = v, .dots = -c(UQS(not.columns))) 
    #or use !!! instead of UQS 
    #tidyr::gather(d, key = k, value = v, .dots = -c(!!!(not.columns))) 

} 
de <- my_gather(mtcars, not.columns = quos(mpg, cyl, disp)) 
head(de, 3) 
# mpg cyl disp k v 
#1 21.0 6 160 hp 110 
#2 21.0 6 160 hp 110 
#3 22.8 4 108 hp 93 
出力で確認する

を行うことができます

de1 <- gather(mtcars, key = k, value = v, -mpg, -cyl, -disp) 
identical(de, de1) 
#[1] TRUE 
+0

これはOPの試行とどのように違いますか? 'UQS' =' !!! '; 'c'はここで違いはありません。 –

+2

@KonradRudolphはい、 'c'は違いですが、私は中かっこの中に置きたいです。 – akrun

+0

OK。どうして?それは非常に明白ではありません –

2

私は "答えは問題ではありません"という答えを提供することができます。実際には、使用されていない列に関する情報を持つ集められた列を指定する方法が必要です。ここに私の方法である:

library(tidyverse) 

negate_columns <- function(.tbl, not.columns) { 
    not_columns <- colnames(select(.tbl, !!!not.columns)) 

    setdiff(colnames(.tbl), not_columns) 
} 

my_gather <- function(d, not.columns) { 
    columns <- negate_columns(d, not.columns) 

    tidyr::gather(d, key = k, value = v, !!!syms(columns)) 
} 

期待どおりに動作します。この方法は:

my_gather(mtcars, not.columns = quos(mpg, cyl, disp)) %>% 
    head(3) 
#> mpg cyl disp k v 
#> 1 21.0 6 160 hp 110 
#> 2 21.0 6 160 hp 110 
#> 3 22.8 4 108 hp 93