Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can tidyr spread function take variable as a select column

Tags:

r

tidyr

tidyr's spread function only takes column names without quotes. Is there a way I can pass in a variable that contains the column name for eg

# 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)

This gives an error

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

Which is solved using match function which gives the required column position

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

But this same approach doesn't work for the spread function

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

Do gather and spread functions take different column specification. gather takes a column index while spread doesn't mention what it wants

like image 567
MySchizoBuddy Avatar asked Nov 09 '22 10:11

MySchizoBuddy


1 Answers

If you want to use standard evaluation 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 this works :

dummy.data %>% spread_("a",var)
#   B  a  b  c  d  e  f  g  h  i  j  k  l  m  n  o  p  q  r  s  t  u  v  w  x  y
# 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
like image 77
Moody_Mudskipper Avatar answered Nov 15 '22 05:11

Moody_Mudskipper