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

问题描述 投票:1回答:1

我知道有gather_(),但它不与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
...

Desired result

   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
...

My effords

google,SO,get(dynamicKey) ......什么都行不通

r tidyr
1个回答
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...
© www.soinside.com 2019 - 2024. All rights reserved.