Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To find whether a column exists in data frame or not

Tags:

r

People also ask

How do I check if a column exists in a data frame?

In order to check if a list of multiple selected columns exist in pandas DataFrame, use set. issubset . For Example, if set(['Courses','Duration']).

How do you find the columns of a data frame?

To access the names of a Pandas dataframe, we can the method columns(). For example, if our dataframe is called df we just type print(df. columns) to get all the columns of the Pandas dataframe. After this, we can work with the columns to access certain columns, rename a column, and so on.

How do I find columns in a DataFrame in R?

To access a specific column in a dataframe by name, you use the $ operator in the form df$name where df is the name of the dataframe, and name is the name of the column you are interested in. This operation will then return the column you want as a vector.


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

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

You could use any:

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

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

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()