在tidyr :: gather中动态设置键或值

时间:2018-02-28 17:04:11

标签: r tidyr

我知道有matches,但它与 dynamicKey = "coolKey" mtcars[,8:11] %>% gather(dynamicKey,values,matches("vs|am")) gear carb dynamicKey values 1 4 4 vs 0 2 4 4 vs 0 3 4 1 vs 1 4 3 1 vs 1 5 3 2 vs 0 6 3 1 vs 1 ... 无关,所以......

   gear carb    coolKey values
1     4    4         vs      0
2     4    4         vs      0
3     4    1         vs      1
4     3    1         vs      1
5     3    2         vs      0
6     3    1         vs      1
...

期望的结果

get(dynamicKey)

我的effords

谷歌,所以,functools.wraps ......没有任何作用

1 个答案:

答案 0 :(得分:2)

您需要使用UQ函数或等效的双重表示法取消引用动态键参数:

library(dplyr)
library(tidyr)
dynamicKey  = "coolKey"

mtcars[,8:11] %>% gather(key = !!dynamicKey,value = values,matches("vs|am"))

输出:

   gear carb coolKey values
1     4    4      vs      0
2     4    4      vs      0
3     4    1      vs      1
4     3    1      vs      1
5     3    2      vs      0
6     3    1      vs      1 ...

同样的事情,但用UQ而不是双重爆炸:

> mtcars[,8:11] %>% gather(key = UQ(dynamicKey),value = values,matches("vs|am"))
   gear carb coolKey values
1     4    4      vs      0
2     4    4      vs      0
3     4    1      vs      1
4     3    1      vs      1
5     3    2      vs      0
6     3    1      vs      1...