Search code examples
rstringends-with

How to select from string charcters ending with a letter and number


I have this kind of dataset

mtcars$drat1 = mean(mtcars$drat)
mtcars$wt1 = mean(mtcars$wt)

I have been trying to build up the code following the rule so that it selects the every element finishing with t and a number.

I have tried this code but I am getting an empty object.

mtcars %>% dplyr::select(ends_with('t[0-9]$'))

How should I modify this?


Solution

  • As the documentation states, the argument for starts_with(), ends_with(), and contains() looks for an exact match. You want to use matches() here, which can accept regex:

    mtcars %>% dplyr::select(matches('t[0-9]$'))
    
    #                       drat1     wt1
    # Mazda RX4           3.596563 3.21725
    # Mazda RX4 Wag       3.596563 3.21725
    # Datsun 710          3.596563 3.21725
    # Hornet 4 Drive      3.596563 3.21725
    # ...
    

    Or in base R:

    mtcars[grep("t[0-9]$", names(xx))]