Reputation: 606
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
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
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