how to use gather_ in tidyr with variables

旧巷老猫 提交于 2019-12-10 16:33:00

问题


I'm using tidyr together with shiny and hence needs to utilize dynamic values in tidyr operations. However I do have trouble using the gather_(), which I think was designed for such case. Minimal example below:

library(tidyr)

df <- data.frame(name=letters[1:5],v1=1:5,v2=10:14,v3=7:11,stringsAsFactors=FALSE)
#works fine
df %>% gather(Measure,Qty,v1:v3)

dyn_1 <- 'Measure'
dyn_2 <- 'Qty'
dyn_err <- 'v1:v3'
dyn_err_1 <- 'v1'
dyn_err_2 <- 'v2'
#error
df %>% gather_(dyn_1,dyn_2,dyn_err)
#error
df %>% gather_(dyn_1,dyn_2,dyn_err_1:dyn_err_2)

after some debug I realized the error happened at melt measure.vars part, but I don't know how to get it work with the ':' there... Please help with a solution and explain a little bit so I could learn more.


回答1:


You are telling gather_ to look for the colume 'v1:v3' not on the separate column ids. Simply change dyn_err <- "v1:v3" to dyn_err <- paste("v", seq(3), sep="").

If you df has different column names (e.g. var_a, qtr_b, stg_c), you can either extract those column names or use the paste function for whichever variables are of interest.

dyn_err <- colnames(df)[2:4]

or

dyn_err <- paste(c("var", "qtr", "stg"), letters[1:3], sep="_")

You need to look at what column names you want and make the corresponding vector.



来源:https://stackoverflow.com/questions/26429582/how-to-use-gather-in-tidyr-with-variables

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