Selecting columns with grep

Hi,
I need to select some of the columns with grep.

grep(pattern=paste0(ABC,"\\d"), x=names(baza), value = FALSE)

The thing is, it works when I have got columns named like DES1, DES2 up to DES10, then it will take all of them.

How to modify this grep that for example it will select DES4 to DES8 ?

Thank you for all the help.

There's probably a more efficient way to do this, but why not just remove DES using stringr::str_sub and then filter matches for the integers 4:8?

(To do this, I don't think you even need to convert the strings "4",...,"8" into integers because R can match integers to strings that only involve integers.)

Hi @Andrzej ,

I created some example data to illustrate a solution (I would advise that you share your own example dataframes in future questions).

library(tidyverse)
#create example dataframe
DF <- matrix(1:100, ncol = 10) %>% as_tibble() %>% rename_with(.cols = everything(), .fn = ~str_replace(., "V", "DES"))

#method 1: using dplyr
DF %>% select(matches("DES[4-8]"))

#method 2: using base R
DF[,grep("DES[4-8]", names(DF))]

I hope it answers your question.

Thank you both very much.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.