Andre Elrico
Andre Elrico

Reputation: 11480

Set key or value dynamically in tidyr::gather

I know there is gather_() but its not working with matches and so ...

    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) ... nothing works

Upvotes: 1

Views: 176

Answers (1)

Stewart Ross
Stewart Ross

Reputation: 1044

You need to unquote the dynamic key argument, either with the UQ function or with the equivalent double-bang notation:

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

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

Output:

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

Same thing but with UQ instead of the double bang:

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

Upvotes: 2

Related Questions