How to combine two rows in R data frame by addition?

R ProgrammingServer Side ProgrammingProgramming

To combine two rows in R data frame by addition, we can follow the below steps −

  • First of all, create a data frame.

  • Then, using plus sign (+) to add two rows and store the addition in one of the rows.

  • After that, remove the row that is not required by subsetting with single square brackets.

Example

Create the data frame

Let’s create a data frame as shown below −

x<-rpois(25,1)
y<-rpois(25,1)
z<-rpois(25,1)
df<-data.frame(x,y,z)
df

Output

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

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

Add two rows

Using plus sign to add row 1 and row 2 then storing the sum in row 1 −

x<-rpois(25,1)
y<-rpois(25,1)
z<-rpois(25,1)
df<-data.frame(x,y,z)
df[1,]<-df[1,]+df[2,]
df

Output

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

Remove the row which is not required

Using single square subsetting to remove 2nd row from data frame df −

x<-rpois(25,1)
y<-rpois(25,1)
z<-rpois(25,1)
df<-data.frame(x,y,z)
df[1,]<-df[1,]+df[2,]
df[-2,]

Output

   x y z
1  2 2 0
3  1 1 2
4  2 0 1
5  2 1 1
6  2 0 1
7  0 1 0
8  1 0 3
9  1 1 4
10 0 0 2
11 0 0 0
12 1 0 3
13 0 0 2
14 1 4 2
15 1 3 3
16 0 2 1
17 1 1 1
18 2 3 1
19 2 1 1
20 1 2 0
21 1 1 0
22 1 0 0
23 2 0 0
24 0 0 1
25 2 0 0
raja
Updated on 16-Nov-2021 05:41:53

Advertisements