How to check if a column exists in a matrix or data frame?

Is there a way to check if a column exists in a matrix or data.frame?

For example: TableA

Name Age Address Contact No. Ben 12 CA 1234567 

How to check if the column "Gender" or "Age" exists before processing the row?

thank

+2
r
Feb 14 '14 at 4:33
source share
1 answer

I hope you understand that the columns "Gender" or "Age" either exist or do not exist for all rows in the data frame?

An easy way to check is to take the names of the data frame and compare the columns in which you are inetrested with the names to see if they are included in this set. For example, some data about your question:

 df <- data.frame(Name = "Ben", Age = 12, Address = "CA", ContactNo = 1234567) 

Note the names attribute for the df data frame:

 names(df) > names(df) [1] "Name" "Age" "Address" "ContactNo" 

Then you can check if the variables of interest are interested in the set of variables in the data frame:

 c("Gender", "Age") %in% names(df) > c("Gender", "Age") %in% names(df) [1] FALSE TRUE 

For the matrix, you need the colnames attribute, which is accessed through the colnames() allocation function, instead of the names and names() attribute.

+4
Feb 14 '14 at 4:39
source share



All Articles