How to add a row in an R data frame at a specific place?


The data collected for the first time is utilised as it is but when we need to go for secondary data to conduct the same or similar study again, we can use new data as well as the primary data. In this type of situations, we might want to randomly organize data rows that includes new and old data. Also, there is a possibility of missing data row which is found at later stage in the study then it can be also added. Hence, a row might be required to added in the existing data frame. This can be done by using rbind function.

Example1

Consider the below data frame −

Live Demo

> ID<-1:20
> Frequency<-rpois(20,5)
> df1<-data.frame(ID,Frequency)
> df1

Output

  ID Frequency
1 1 6
2 2 6
3 3 4
4 4 0
5 5 5
6 6 5
7 7 5
8 8 4
9 9 4
10 10 6
11 11 6
12 12 4
13 13 4
14 14 5
15 15 8
16 16 5
17 17 2
18 18 4
19 19 3
20 20 5

Adding a row at the 11th position in the data frame −

Example

> df1<-rbind(df1[1:10,],c(NA,2),df1[11:nrow(df1),],make.row.names=FALSE)
> df1

Output

ID Frequency
1 1 6
2 2 6
3 3 4
4 4 0
5 5 5
6 6 5
7 7 5
8 8 4
9 9 4
10 10 6
11 NA 2
12 11 6
13 12 4
14 13 4
15 14 5
16 15 8
17 16 5
18 17 2
19 18 4
20 19 3
21 20 5

Example2

Live Demo

> x1<-sample(LETTERS[1:4],20,replace=TRUE)
> x2<-sample(c("Hot","Cool"),20,replace=TRUE)
> df2<-data.frame(x1,x2)
> df2

Output

  x1 x2
1 D Cool
2 B Cool
3 C Cool
4 B Hot
5 A Hot
6 D Hot
7 A Hot
8 B Hot
9 C Hot
10 B Hot
11 A Cool
12 C Hot
13 A Hot
14 C Hot
15 C Hot
16 C Hot
17 C Hot
18 B Cool
19 C Hot
20 B Hot

Adding a row at the 3rd position in the data frame −

Example

> df2<-rbind(df2[1:2,],c("A","Hot"),df2[3:nrow(df2),],make.row.names=FALSE)
> df2

Output

x1 x2
1 D Cool
2 B Cool
3 A Hot
4 C Cool
5 B Hot
6 A Hot
7 D Hot
8 A Hot
9 B Hot
10 C Hot
11 B Hot
12 A Cool
13 C Hot
14 A Hot
15 C Hot
16 C Hot
17 C Hot
18 C Hot
19 B Cool
20 C Hot
21 B Hot

Updated on: 02-Jan-2021

389 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements