r - grepl vs比赛

时间:2016-07-02 16:07:43

标签: r dplyr grepl

我使用matches包中的dplyr函数遇到了一些问题。

从这个数据集中,我想提取以enj

开头的列名
    enj1 enj2 Enjm
bbc    1    1    2
bca    1    1    2

使用grepl,我可以这样做

dt[, grepl('enj', colnames(dt))] 

并获取

    enj1 enj2
bbc    1    1
bca    1    1

但是,matches功能给我正确答案

library(dplyr) 

dt %>% select(matches('enj') )
# or 
dt %>% select(matches('^enj') )

知道为什么吗?

dt = structure(list(enj1 = structure(c(1L, 1L), .Names = c("bbc", 
"bca"), .Label = "1", class = "factor"), enj2 = structure(c(1L, 
1L), .Names = c("bbc", "bca"), .Label = "1", class = "factor"), 
    Enjm = structure(c(1L, 1L), .Names = c("bbc", "bca"), .Label = "2", class = "factor")), .Names = c("enj1", 
"enj2", "Enjm"), row.names = c("bbc", "bca"), class = "data.frame")

1 个答案:

答案 0 :(得分:3)

这是因为你没有设置ignore.case = F

> dt %>% select(matches('^enj',  ignore.case = F) )
    enj1 enj2
bbc    1    1
bca    1    1
>