Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to check whether a column exists in an R data frame?
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
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"
Advertisements
