'R: How to select columns with dplyr matches?

I'm a beginner in using regex and dplyr::matches() so this is probably a silly question:

How to select columns with leading zero digits in the name using dplyr::matches()?

An example data:

d <- data.frame(
    var_001 = c( 1, 2, 3 ),
    var_012 = c( 4, 5, 6 ),
    var_001_b = c( 11, 22, 33 ),
    var = c( 7, 8, 9 )
)

The pattern I've built:

pattern <- 'var_[0*\\d+]{3}$'

If I use str_match(), I'm able to detect the correct names:

str_match( names( d ), pattern )

#>      [,1]     
#> [1,] "var_001"
#> [2,] "var_012"
#> [3,] NA       
#> [4,] NA       

However, using matches() in select() does not return any columns:

d %>%
    select( matches( pattern ) )

#> # A tibble: 3 x 0


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source