How to check whether a column exists in an R data frame?

R ProgrammingServer Side ProgrammingProgramming

If we have very large data set then it is highly that we forget the column names, therefore, we might want to check whether a particular column exists in the data frame or not if we know the column name. For this purpose, we can use grep function that will result the column name if exists in the data frame otherwise 0. To understand how it works check out the below examples.

Example1

 Live Demo

Consider the below data frame −

Gender<−sample(c("Male","Female"),20,replace=TRUE)
Y<−rpois(20,5)
df1<−data.frame(Gender,Y)
df1

Output

Gender Y
1 Male 7
2 Female 4
3 Male 3
4 Male 3
5 Male 4
6 Female 7
7 Male 10
8 Female 4
9 Female 4
10 Female 6
11 Female 6
12 Female 2
13 Male 6
14 Female 4
15 Female 2
16 Male 5
17 Male 1
18 Male 8
19 Female 5
20 Female 2

Checking whether the column Gender exists in df1 or not −

Example

grep("Gender",names(df1),value=TRUE)

Output

[1] "Gender"

Checking whether the column Sex exists in df1 or not −

Output

grep("Sex",names(df1),value=TRUE)
character(0)

Example2

 Live Demo

ID<−1:20
Weather<−sample(c("Summer","Rainy","Winter"),20,replace=TRUE)
df2<−data.frame(ID,Weather)
df2

Output

ID Weather
1 1 Summer
2 2 Rainy
3 3 Summer
4 4 Summer
5 5 Winter
6 6 Summer
7 7 Rainy
8 8 Rainy
9 9 Rainy
10 10 Winter
11 11 Winter
12 12 Rainy
13 13 Winter
14 14 Winter
15 15 Summer
16 16 Winter
17 17 Rainy
18 18 Summer
19 19 Winter
20 20 Rainy

Checking whether the column atmosphere exists in df2 or not −

grep("atmosphere",names(df2),value=TRUE)
character(0)

Checking whether the column Weather exists in df2 or not −

Example

grep("Weather",names(df2),value=TRUE)

Output

[1] "Weather"
raja
Published on 09-Feb-2021 11:55:17
Advertisements