Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subset a vector of column names by a particular sample prefix

Tags:

r

Lets say I have a data frame that looks like this

ca01<- c(1:10)
ca02<- c(2:11)
ca03<- c(3:12)
stuff.1<- rep('test',10)
other<- rep(9,10)

data<- data.frame(ca01,ca02,ca03,stuff.1,other)

I then create a vector that contains the column names

samps<- colnames(data)

I then want to filter this vector to only contain items that begin with the prefix "ca". I do not want to exclude stuff.1 and other by writing individual lines of code that remove these specifically, so something like

samps<-samps[samps!='stuff.1']
samps<-samps[samps!='other']

would not be suitable.

like image 958
colin Avatar asked Jan 08 '23 16:01

colin


1 Answers

Try using grepl

> Names <- colnames(data)
> Names[grepl("^ca", Names)]
[1] "ca01" "ca02" "ca03"
like image 142
Jilber Urbina Avatar answered Feb 13 '23 11:02

Jilber Urbina