简体   繁体   中英

how to use gather_ in tidyr with variables

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM