仅匹配dplyr matches()辅助函数的完全匹配

Jos*_*erg 2 r dplyr

我现在用的matches()辅助函数作为参数的一部分select()dplyr功能.

对于假设df数据框,该函数如下所示:

select(df, variable_1_name, matches("variable_2_name"))
Run Code Online (Sandbox Code Playgroud)

至少当我正在使用它时,variable_2_name必须作为字符串传递给select().

但是,如果df匹配中存在另一个变量"variable_2_name",例如"variable_2_name_recode",那么matches()将匹配这两个变量.是否可以仅使用dplyr函数匹配完全匹配,或者使用不同的方法?

ste*_*veb 6

当然,当不需要字符串时,您可以执行以下操作:

select(df, variable_1_name, variable_2_name)
Run Code Online (Sandbox Code Playgroud)

matches 采取一种模式,你可以尝试

# '^' anchors the match at the beginning of the string and
# '$' anchors the match at the end of the string.
select(df, variable_1_name, matches("^variable_2_name$"))
Run Code Online (Sandbox Code Playgroud)

这应该完全匹配variable_2_name.

如果你有一个函数根据列名的字符串进行选择,你可以执行以下操作(如注释中的Psidom所述).第一个例子比较简单,第二个例子更像是你要找的东西.

### Example 1
### Given function and the 'df' with the column 'variable_2_name'
my_func <- function(df, colname) { df %>% select_(colname) }
my_func(df, 'variable_2_name') # Call with column name string

### Example 2
### Using one column name that is not a string with a string column name string.
### 'df' has columns 'variable_1_name' and 'variable_2_name'
my_func <- function(df, colname) {
    df %>% select_(quote(variable_1_name), colname)
}
### Call with column name returns 2 columns of data
### 'variable_1_name' and 'variable_2_name'
my_func(df, 'variable_2_name')
Run Code Online (Sandbox Code Playgroud)