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]
}
}
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', ...)))
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.
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.
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]
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With