How tidyr propagation function takes a variable as a select column

The tidyr spread function uses column names without quotes. Is there a way to pass a variable containing the column name for example

# example using gather() library("tidyr") dummy.data <- data.frame("a" = letters[1:25], "B" = LETTERS[1:5], "x" = c(1:25)) dummy.data var = "x" dummy.data %>% gather(key, value, var) 

It gives an error

 Error: All select() inputs must resolve to integer column positions. The following do not: * var 

What is solved with the match function, which gives the desired column position

 dummy.data %>% gather(key, value, match(var, names(.))) 

But the same approach does not work for the distribution function

 dummy.data %>% spread(a, match(var, names(.))) Error: Invalid column specification 

Collect and distribute functions perform different column specifications. gather accepts the index of the column, while distribution doesn’t mention what it wants

+5
source share
1 answer

If you want to use the standard grade, you need to use gather_ or spread_

These 2 give the same results.

 dummy.data %>% gather_("key", "value", var) dummy.data %>% gather(key, value, match(var, names(.))) 

And it works:

 dummy.data %>% spread_("a",var) # B abcdefghijklmnopqrstu vwxy # 1 A 1 NA NA NA NA 6 NA NA NA NA 11 NA NA NA NA 16 NA NA NA NA 21 NA NA NA NA # 2 B NA 2 NA NA NA NA 7 NA NA NA NA 12 NA NA NA NA 17 NA NA NA NA 22 NA NA NA # 3 C NA NA 3 NA NA NA NA 8 NA NA NA NA 13 NA NA NA NA 18 NA NA NA NA 23 NA NA # 4 D NA NA NA 4 NA NA NA NA 9 NA NA NA NA 14 NA NA NA NA 19 NA NA NA NA 24 NA # 5 E NA NA NA NA 5 NA NA NA NA 10 NA NA NA NA 15 NA NA NA NA 20 NA NA NA NA 25 
+1
source

All Articles