Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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

For example: TableA

Name    Age    Address     Contact No.
Ben     12     CA           1234567

How can I check if a column "Gender" or "Age" exist before I process a row?

Thanks

like image 846
Ianthe Avatar asked Oct 15 '25 19:10

Ianthe


1 Answers

I hope you realise that columns "Gender" or "Age" either do or don't 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 you are inetrested with the names to see if they are included in that set. For example, some data as per your question:

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

Note the names attribute for the data frame df:

names(df)

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

Then you can check to see if the variables of interest are 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 a matrix, you need the colnames attribute, accessed via the colnames() extractor function, instead of the names attribute and names().

like image 176
Gavin Simpson Avatar answered Oct 17 '25 11:10

Gavin Simpson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!