How to create a clone of a data frame in R without data values?


To create a clone of a data frame in R without data values, we can follow the below steps −

  • First of all, create a data frame.

  • Then, create the clone of the data frame by subsetting zero rows.

Example 1

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x1<-rnorm(25)
x2<-rnorm(25)
x3<-rnorm(25)
df1<-data.frame(x1,x2,x3)
df1

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

      x1           x2         x3
1  -0.88372447 2.17866787 0.844763742
2  -0.90009212 -2.95877962 0.347696732
3   1.72333313 0.08088824 0.913762586
4   1.90904216 0.11013780 0.608274553
5  -0.77714120 0.21344833 -0.607547988
6  -1.30230526 -1.55781961 0.179658071
7   2.62349517 0.21621155 -1.908409419
8   0.22962891 0.18766382 0.502946258
9   0.18674989 1.25862213 0.968899153
10 0.07613663 0.52351778 -0.875737126
11 1.40486019 1.11545428 -2.136024539
12 -0.19172224 -0.95750224 -1.522827582
13 1.45939216 -0.12440558 -1.113118208
14 -0.22065545 0.19173783 1.240983896
15 0.50514589 0.27221725 0.003481935
16 -1.03349701 -0.69381446 -1.237794586
17 0.17047347 1.47917192 0.555699119
18 1.20066816 -0.61176702 -2.183149349
19 -0.16340591 -1.61430997 -0.247024457
20 1.28247586 0.40249011 1.112856928
21 2.72719639 0.66455545 -0.341673237
22 0.94192422 0.94412707 1.305438342
23 -0.24861404 -0.94626080 1.795323871
24 0.09647886 -0.24828845 -1.167835227
25 -0.43393094 -1.32843647 -1.152287625

Create clone of the data frame

Use single square brackets for subsetting to create the clone of df1 without data −

 Live Demo

x1<-rnorm(25)
x2<-rnorm(25)
x3<-rnorm(25)
df1<-data.frame(x1,x2,x3)
df1_new<-df1[0,]
df1_new

Output

[1] x1 x2 x3
<0 rows> (or 0-length row.names)

Example 2

Create the data frame

Let's create a data frame as shown below −

 Live Demo

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

Output

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

Create clone of the data frame

Use single square brackets for subsetting to create the clone of df2 without data −

 Live Demo

y1<-rpois(25,2)
y2<-rpois(25,5)
y3<-rpois(25,1)
y4<-rpois(25,2)
df2<-data.frame(y1,y2,y3,y4)
df2_new<-df2[0,]
df2_new

Output

[1] y1 y2 y3 y4
<0 rows> (or 0-length row.names)

Updated on: 14-Aug-2021

390 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements