使用dplyr的select引用变量名的位置 [英] Using dplyr's select where variable names are quoted
问题描述
通常,我想选择一个变量子集,其中子集是函数的结果。在这种简单的情况下,我首先获得所有与宽度特征有关的变量名
Often I'll want to select a subset of variables where the subset is the result of a function. In this simple case, I first get all the variable names which pertain to width characteristics
library(dplyr)
library(magrittr)
data(iris)
width.vars <- iris %>%
names %>%
extract(grep(".Width", .))
返回值:
>width.vars
[1] "Sepal.Width" "Petal.Width"
能够使用这些返回值作为选择列的方式将很有用(而且我知道 contains()
及其同级物存在,我想执行许多更复杂的子集,并且出于本示例的目的,使本示例变得微不足道。
It would be useful to be able to use these returns as a way to select columns (and while I'm aware that contains()
and its siblings exist, there are plenty of more complicated subsets I would like to perform, and this example is made trivial for the purpose of this example.
如果我试图使用此功能作为选择列的方式,则会发生以下情况:
If I was to attempt to use this function as a way to select columns, the following happens:
iris %>%
select(Species,
width.vars)
Error: All select() inputs must resolve to integer column positions.
The following do not:
* width.vars
如何使用 dplyr :: select
带有以字符串形式存储的变量名向量?
How can I use dplyr::select
with a vector of variable names stored as strings?
推荐答案
在 dplyr
内,大多数命令都有一个备用版本,其后缀为'_',可以接受字符串作为输入。在这种情况下,请选择 select _
。这些通常是在以编程方式使用 dplyr
时必须使用的。
Within dplyr
, most commands have an alternate version that ends with a '_' that accept strings as input; in this case, select_
. These are typically what you have to use when you are utilizing dplyr
programmatically.
iris %>% select_(.dots=c("Species",width.vars))
这篇关于使用dplyr的select引用变量名的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!