Select columns based on the first letter of columns using grep or grepl in r

I am trying to use a package dplyr

to select all columns starting with i. I have the following code:

dat<-select(newdat1,starts_with("i"))

      

and the names for my data are:

> colnames(newdat)
[1] "i22" "i21" "i20" "i24"

      

It's just a coincidence, in this case they all start with an i, as in other cases there will be more variety; thus I want to automate the process. The problem is my code using is dplyr

correct; however I am having problems with the package, so I was wondering if / how to accomplish the same task with grep or grepl or something actually using the base package. Thank!

+3


source to share


1 answer


With base R you can use grep

to match column names. you can use

dat<-newdat1[,grep("^i", colnames(newdat1))]

      



perform a startup with a similar request. You can use any regex you want as a pattern in grep()

.

+9


source







All Articles