How to add a row to a frame from another data frame in R?


Sometimes we want to add new data to original data frame in situations such as we need more data for analysis, looking for comparison between small size and large size data, or some data is missing in the original data and hence need more to be added from other data sets. One such thing would be adding a new to an existing data frame from another data frame. It can be done with the help of rbind function as shown in the below example.

Consider the below data frames df1 and df2 −

Example

 Live Demo

x<-rnorm(20,5,0.32)
y<-rnorm(20)
df1<-data.frame(x,y)
df1

Output

       x        y
1  5.117123   1.74829193
2  4.960077   0.09355200
3  4.753610  -0.66495815
4  4.670624   0.82040576
5  5.086504   0.09799773
6  4.539778  -1.61979527
7  5.036810   1.54677737
8  4.928225  -0.35618054
9  4.562703  -0.07945785
10 5.182163  -1.22423063
11 4.631324  -0.64323915
12 5.014459   0.37210137
13 5.051155   0.96915033
14 4.674217  -1.71893532
15 4.833822   0.30810150
16 5.031242  -0.89478778
17 4.943864   1.82751206
18 4.501895  -0.15018344
19 5.193700  -0.51444521
20 5.233756  -1.51400187

Example

 Live Demo

x<-rnorm(20,5,1.1)
y<-rnorm(20)
df2<-data.frame(x,y)
df2

Output

      x        y
1  1.443246  -0.19426625
2  4.264331   0.14100808
3  6.498757   0.04043399
4  4.806667  -0.28814785
5  2.425545   0.02902172
6  5.304705   0.38877674
7  4.571713  -0.44393690
8  5.279155   0.44745342
9  5.170824   0.51590942
10 4.807848  -1.24689208
11 4.965998  -0.95738511
12 3.537272  -0.03154153
13 4.996014   1.56962626
14 4.511364   1.06805235
15 2.419139   1.89419766
16 6.505101   0.78259844
17 7.823775   0.05896647
18 5.837392   0.67802181
19 4.830523  -0.71292456
20 3.894001   0.05865083

Adding one row from df2 in df1 −

Example

df1<-rbind(df1,df2[1,])
df1

Output

       x       y
1  5.117123   1.74829193
2  4.960077   0.09355200
3  4.753610  -0.66495815
4  4.670624   0.82040576
5  5.086504   0.09799773
6  4.539778  -1.61979527
7  5.036810   1.54677737
8  4.928225  -0.35618054
9  4.562703  -0.07945785
10 5.182163  -1.22423063
11 4.631324  -0.64323915
12 5.014459   0.37210137
13 5.051155   0.96915033
14 4.674217  -1.71893532
15 4.833822   0.30810150
16 5.031242  -0.89478778
17 4.943864   1.82751206
18 4.501895  -0.15018344
19 5.193700  -0.51444521
20 5.233756  -1.51400187
21 1.443246  -0.19426625

Updated on: 08-Feb-2021

905 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements