如何在tidyverse的gather与select函数中使用变量?
嘿,我知道你在tidyverse里用变量存列范围(比如x <- "mpg:am")时,想在gather和select里用它却碰壁了——别担心,这是因为get()不是干这个活的工具,它是用来获取全局环境里的对象的,而我们需要的是解析列选择表达式,下面给你具体的解决方案:
针对
select()的解决方法 你有两种简单的方式可以实现:
方法1:用表达式注入
借助rlang::parse_expr()把字符串转换成R能识别的列范围表达式,再用!!(bang-bang操作符)注入到select中:
library(tidyverse) x <- "mpg:am" mtcars %>% select(!!rlang::parse_expr(x)) %>% head()
方法2:用all_of()函数
all_of()是tidyselect包专门用来处理字符串类型列选择的工具,它能正确识别"mpg:am"这种范围格式的字符串:
mtcars %>% select(all_of(x)) %>% head()
针对
gather()的解决方法 gather的列选择逻辑和select完全一致,所以同样可以用上面两种方法:
方法1:表达式注入
mtcars %>% gather(type, value, !!rlang::parse_expr(x)) %>% head()
方法2:all_of()函数
mtcars %>% gather(type, value, all_of(x)) %>% head()
额外推荐:使用
pivot_longer()替代gather() 要注意哦,gather已经是tidyverse的“退役”函数了,官方现在更推荐用pivot_longer(),用法类似,灵活性更高:
mtcars %>% pivot_longer(cols = !!rlang::parse_expr(x), names_to = "type", values_to = "value") %>% head()
这些方法的核心思路都是告诉dplyr:不要把x当成普通字符串,要把它解析成列选择的规则来执行,这样就能正确识别mpg到am之间的所有列啦~
内容的提问来源于stack exchange,提问作者cephalopod
相关产品推荐
相关产品推荐

