To find whether a column exists in data frame or not

R

R Problem Overview


I have a data.frame with the name "abcframe"

     a  b  c
     1  1  1
     2  2  3

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

R Solutions


Solution 1 - R

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's in there!\n");
}

Solution 2 - R

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

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

To get the names of the columns:

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

Use %in% to check for membership:

"d" %in% names(dat)
[1] FALSE

Or use `grepl` to check for a match:

grepl("d", names(dat))
[1] FALSE FALSE FALSE

Solution 3 - R

You could use any:

> names(dat)
[1] "a" "b" "c"
> any(names(dat) == 'b')
[1] TRUE
> any(names(dat) == 'B')
[1] FALSE

Solution 4 - R

You could also use if(!is.null(abcframe$d)) to test whether d exists in abcframe.

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

if (!is.null(dat$d)) {
  print("d exists")
} else {
  print("d does not exist")
}
if (!is.null(dat$a)) {
  print("a exists")
} else {
  print("a does not exist")
}

Solution 5 - R

A tidyverse approach might be more readable for some people, and therefore better to remember.

You would search for the variable by str_detect which returns a logical vector like grepl, and then collapse this by the base R function any which returns TRUE if there was at least one TRUE value.

dat %>% names %>% str_detect("d") %>% any()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSunny SunnyView Question on Stackoverflow
Solution 1 - Ruser554546View Answer on Stackoverflow
Solution 2 - RAndrieView Answer on Stackoverflow
Solution 3 - RTomasz PikView Answer on Stackoverflow
Solution 4 - RJacksonView Answer on Stackoverflow
Solution 5 - RAgile BeanView Answer on Stackoverflow