How to create a row sum and a row product column in an R data frame?

R ProgrammingServer Side ProgrammingProgramming

To create a row sum and a row product column in an R data frame, we can use rowSums function and the star sign (*) for the product of column values inside the transform function. For example, if we have a data frame df that contains x, y, z then the column of row sums and row product can be created as:

transform(df,RowSums=rowSums(df),RowProducts=x*y*z)

Example

Consider the below data frame:

Live Demo

> set.seed(3251)
> x1<-rpois(20,2)
> y1<-rpois(20,5)
> z1<-rpois(20,6)
> a1<-rpois(20,8)
> b1<-rpois(20,7)
> df1<-data.frame(x1,y1,z1,a1,b1)
> df1

Output

x1 y1 z1 a1 b1
1 2 4 10 10 5
2 0 9 5 5 8
3 4 7 6 12 9
4 2 3 3 11 2
5 2 5 11 8 6
6 2 4 9 9 12
7 1 8 3 7 6
8 2 7 7 6 3
9 3 9 10 13 8
10 1 8 7 12 5
11 0 3 9 7 7
12 2 4 9 10 5
13 3 5 5 8 7
14 3 6 4 4 10
15 1 5 11 11 4
16 0 6 7 6 6
17 3 2 10 10 5
18 2 5 4 7 14
19 4 6 3 4 7
20 1 7 6 13 6

Creating row sums and row products column in df1:

Example

> transform(df1,RowSums=rowSums(df1),RowProducts=x1*y1*z1*a1*b1)

Output

x1 y1 z1 a1 b1 RowSums RowProducts
1 2 4 10 10 5 31 4000
2 0 9 5 5 8 27 0
3 4 7 6 12 9 38 18144
4 2 3 3 11 2 21 396
5 2 5 11 8 6 32 5280
6 2 4 9 9 12 36 7776
7 1 8 3 7 6 25 1008
8 2 7 7 6 3 25 1764
9 3 9 10 13 8 43 28080
10 1 8 7 12 5 33 3360
11 0 3 9 7 7 26 0
12 2 4 9 10 5 30 3600
13 3 5 5 8 7 28 4200
14 3 6 4 4 10 27 2880
15 1 5 11 11 4 32 2420
16 0 6 7 6 6 25 0
17 3 2 10 10 5 30 3000
18 2 5 4 7 14 32 3920
19 4 6 3 4 7 24 2016
20 1 7 6 13 6 33 3276

Let’s have a look at another example:

Example

Live Demo

> x2<-sample(0:9,20,replace=TRUE)
> y2<-sample(0:9,20,replace=TRUE)
> z2<-sample(0:9,20,replace=TRUE)
> a2<-sample(0:9,20,replace=TRUE)
> b2<-sample(0:9,20,replace=TRUE)
> df2<-data.frame(x2,y2,z2,a2,b2)
> df2

Output

x2 y2 z2 a2 b2
1 3 2 9 5 9
2 9 9 3 3 8
3 7 7 9 0 3
4 8 0 2 1 8
5 7 5 3 0 8
6 4 5 3 8 2
7 2 2 0 7 0
8 7 7 9 5 9
9 2 9 3 0 2
10 4 4 5 8 6
11 3 1 0 6 7
12 6 1 5 1 9
13 0 3 1 6 3
14 3 3 3 2 4
15 6 7 8 3 1
16 7 1 7 4 4
17 3 3 8 4 5
18 2 6 1 8 1
19 0 2 1 7 6
20 8 6 2 8 6

Creating row sums and row products column in df2:

Example

> transform(df2,RowSums=rowSums(df2),RowProducts=x2*y2*z2*a2*b2)

Output

x2 y2 z2 a2 b2 RowSums RowProducts
1 3 2 9 5 9 28 2430
2 9 9 3 3 8 32 5832
3 7 7 9 0 3 26 0
4 8 0 2 1 8 19 0
5 7 5 3 0 8 23 0
6 4 5 3 8 2 22 960
7 2 2 0 7 0 11 0
8 7 7 9 5 9 37 19845
9 2 9 3 0 2 16 0
10 4 4 5 8 6 27 3840
11 3 1 0 6 7 17 0
12 6 1 5 1 9 22 270
13 0 3 1 6 3 13 0
14 3 3 3 2 4 15 216
15 6 7 8 3 1 25 1008
16 7 1 7 4 4 23 784
17 3 3 8 4 5 23 1440
18 2 6 1 8 1 18 96
19 0 2 1 7 6 16 0
20 8 6 2 8 6 30 4608
raja
Published on 07-Nov-2020 07:45:04
Advertisements