How to add rows in an R data frame?

R ProgrammingServer Side ProgrammingProgramming

To add rows in an R data frame, we can follow the below steps −

  • First of all, create a data frame.

  • Then, use rbind function and the vectors that will be added as rows to the data frame.

Example

Create the data frame

Let’s create a data frame as shown below −

x<-rpois(25,5)
y<-rpois(25,2)
df<-data.frame(x,y)
df

Output

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

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

Add rows in the data frame

Using rbind function and the vectors to add rows in the data frame as shown below −

x<-rpois(25,5)
y<-rpois(25,2)
df<-data.frame(x,y)
df<-rbind(df,c(5,5),c(2,1),c(0,1),c(5,4),c(3,6))
df

Output

    x y
1   9 3
2   4 1
3   5 0
4   8 1
5   5 2
6   6 3
7   7 2
8   3 4
9   5 1
10  2 2
11  5 2
12  2 2
13  8 2
14 12 4
15  7 4
16  3 2
17  4 0
18  8 2
19  6 1
20  2 4
21  3 1
22  4 1
23  4 1
24  4 3
25  2 2
26  5 5
27  2 1
28  0 1
29  5 4
30  3 6
raja
Published on 12-Nov-2021 06:47:21
Advertisements