To determine if a column exists in a data frame or not

I have data.frame named "abcframe"

abc 1 1 1 2 2 3 

How can I determine whether or not a column exists in a given data frame? For example, I would like to find if column d exists in the data.frame abcframe file.

+62
r
Apr 23 2018-12-12T00:
source share
3 answers

Assuming that the name of your data frame is dat and that your column name to check is "d" , you can use the %in% operator:

 if("d" %in% colnames(dat)) { cat("Yep, it in there!\n"); } 
+107
Apr 23 2018-12-12T00:
source share

You have a number of options, including using %in% and grepl :

 dat <- data.frame(a=1:2, b=2:3, c=4:5) dat abc 1 1 2 4 2 2 3 5 

To get column names:

 names(dat) [1] "a" "b" "c" 

Use %in% to verify ownership:

 "d" %in% names(dat) [1] FALSE Or use `grepl` to check for a match: grepl("d", names(dat)) [1] FALSE FALSE FALSE 
+18
Apr 23 2018-12-12T00:
source share

You can use any :

 > names(dat) [1] "a" "b" "c" > any(names(dat) == 'b') [1] TRUE > any(names(dat) == 'B') [1] FALSE 
0
Dec 20 '17 at 22:56
source share



All Articles