8

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]
  }
}
4
  • 4
    try indx <- grepl('Fld', colnames(data)) would be enough to test. If you want to extract the columns, data[indx] or the column names colnames(data)[indx]
    – akrun
    Aug 6, 2015 at 10:15
  • Why are you indexing by [0]? That returns an empty vector every time. I think you want varnames[i]. Also, its print(varnames[i]) with the parens. However, akrun's solution is superior to the loop.
    – Josh
    Aug 6, 2015 at 10:24
  • thanks for the catch. using the zero index was a typo! and agreed - akun's solution is nice! Aug 6, 2015 at 11:36
  • I posted the comment as a solution.
    – akrun
    Aug 9, 2015 at 15:21

3 Answers 3

19

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]
3

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")
}
3

Making more simple !

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.