How can tidyr spread function take variable as a select column

隐身守侯 提交于 2019-12-06 02:14:33

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/31136536/how-can-tidyr-spread-function-take-variable-as-a-select-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!