To find whether a column exists in data frame or not

You could use any:

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

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

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");
}

Tags:

R