user3725021
user3725021

Reputation: 606

Test if column name contains string in R

I'm attempting to test if each of the column names in my dataframe contain a particular string (in this case "Fld". My attempt below is not compiling and I'm not sure where I'm going wrong. Any help would be appreciated.

varnames <-colnames(data)
for (i in 1:len(varnames)){
  if grepl("Fld",varnames[i])==TRUE {
    print varnames[i]
  }
}

Upvotes: 9

Views: 30268

Answers (3)

Hamid Alvi
Hamid Alvi

Reputation: 55

Making more simple !

data[grepl('Fld', colnames(data))]

Upvotes: 3

amc
amc

Reputation: 833

If you are just wanting to 'test if [a] column name contains a string' in R, I would use the any() function around @akrun's nice answer:

if(any(grepl("Fld", colnames(data)))){
   print("True")
}

Upvotes: 3

akrun
akrun

Reputation: 887118

We can use grep to get the index of column names that have 'Fld'

indx <- grepl('Fld', colnames(data))

and use that to subset the 'data'

 data[indx]

Upvotes: 20

Related Questions