How to check whether a data frame exists or not in R?


Sometimes we keep writing codes in the programming console and suddenly we need to use something that was used in the upper side of programming console then recalling it becomes a little ambiguous if we forget about it. In this case, we might want to check whether something exists or not and that something could be a data frame in R programming. For this purpose, we can use the below syntax −

Syntax

exists("data_frame_name")&&is.data.frame(get("data_frame_name "))

Consider the below data frame −

Example

 Live Demo

set.seed(101)
x1<-rnorm(20,1,0.5)
x2<-rnorm(20,1,0.25)
df1<-data.frame(x1,x2)
df1

Output

x1 x2
1 0.83698175 0.9590611
2 1.27623093 1.1771305
3 0.66252808 0.9330049
4 1.10717973 0.6340196
5 1.15538461 1.1861090
6 1.58698314 0.6474025
7 1.30939493 1.1167669
8 0.94363284 0.9701700
9 1.45851414 1.1168097
10 0.88837032 1.1245339
11 1.26322405 1.2237343
12 0.60257778 1.0697880
13 1.71387777 1.2519664
14 0.26659015 0.4817234
15 0.88165831 1.2974633
16 0.90333102 0.8189064
17 0.57512263 1.0419959
18 1.02923275 1.2300838
19 0.59116482 0.5820988
20 -0.02515391 1.1121173
exists("df1")&&is.data.frame(get("df1"))
[1] TRUE

Let’s have a look at another example −

Example

 Live Demo

y1<-rpois(20,1)
y2<-rpois(20,5)
y3<-rpois(20,2)
y4<-rpois(20,8)
df2<-data.frame(y1,y2,y3,y4)
df2

Output

   y1 y2  y3 y4
1  2   2  2  11
2  0   4  1  8
3  1   1  1  9
4  0   2  2  4
5  2   8  0  8
6  2   6  3  4
7  0   5  2  11
8  0   5  3  11
9  0   5  5  9
10 2   5  1  7
11 3   4  2  9
12 0   5  0  8
13 0   6  4  13
14 2  5   2  8
15 1  3   1  9
16 0  3  1  10
17 0  6  1  7
18 1  3  3  9
19 0  8  0  5
20 1  4  2  9


exists("df2")&&is.data.frame(get("df2"))
[1] TRUE

Updated on: 09-Oct-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements