Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if column name contains string in R

Tags:

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]
  }
}
like image 962
user3725021 Avatar asked Aug 06 '15 10:08

user3725021


People also ask

How do you see if a value is in a column in R?

You can use the following basic syntax to find the rows of a data frame in R in which a certain value appears in any of the columns: library(dplyr) df %>% filter_all(any_vars(. %in% c('value1', 'value2', ...)))

How do I use Colnames in R?

Method 1: using colnames() methodcolnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector. The new name replaces the corresponding old name of the column in the data frame.

How do I find column names in R?

To find the column names and row names in an R data frame based on a condition, we can use row. names and colnames function. The condition for which we want to find the row names and column names can be defined inside these functions as shown in the below Examples.


2 Answers

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]
like image 97
akrun Avatar answered Sep 27 '22 22:09

akrun


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")
}
like image 31
amc Avatar answered Sep 27 '22 21:09

amc