如何在带有变量的 tidyr 中使用 gather_ [英] how to use gather_ in tidyr with variables

查看:22
本文介绍了如何在带有变量的 tidyr 中使用 gather_的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 tidyr 与闪亮一起使用,因此需要在 tidyr 操作中使用动态值.但是我确实在使用gather_()时遇到了麻烦,我认为它是为这种情况设计的.下面的最小示例:

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)

经过一些调试后,我意识到错误发生在melt measure.vars 部分,但我不知道如何让它与':' 一起工作......请帮助提供解决方案并稍微解释一下,以便我了解更多信息.

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.

推荐答案

您正在告诉 gather_ 寻找不在单独列中的列 'v1:v3'身份证.只需将 dyn_err <- "v1:v3" 更改为 dyn_err <- paste("v", seq(3), sep="").

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="").

如果您 df 有不同的列名(例如 var_a、qtr_b、stg_c),您可以提取这些列名或使用 paste 函数来处理属于兴趣.

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]

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.

这篇关于如何在带有变量的 tidyr 中使用 gather_的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆