How to create a column in an R data frame that contains the multiplication of two columns?


Sometimes we need the multiplication of two columns and create a new column so that the multiplication can be used further for analysis. For example, to calculate BMI we need mass and height and the height is squared, therefore, we would be needing the square of height. For this purpose, we can either multiply height with height or simply take the square both the ways work. Hence, if only have height column in an R data frame then we can multiply it with itself.

Example

Consider the below data frame −

Live Demo

> set.seed(957)
> x<-rpois(20,1)
> y<-rpois(20,5)
> z<-rpois(20,3)
> df<-data.frame(x,y,z)
> df

Output

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

Creating new columns that has multiplication of different columns −

Example

Live Demo

> df$xy<-df$x*df$y
> df

Output

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

Example

Live Demo

> df$xz<-df$x*df$z
> df

Output

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

Example

Live Demo

> df$yz<-df$y*df$z
> df

Output

x y z xy xz yz
1 0 1 3 0 0 3
2 0 7 3 0 0 21
3 0 6 7 0 0 42
4 3 7 3 21 9 21
5 1 3 7 3 7 21
6 0 3 4 0 0 12
7 1 3 5 3 5 15
8 0 4 2 0 0 8
9 0 5 0 0 0 0
10 0 4 3 0 0 12
11 0 3 7 0 0 21
12 0 8 3 0 0 24
13 1 7 5 7 5 35
14 1 5 5 5 5 25
15 1 10 7 10 7 70
16 0 5 3 0 0 15
17 0 7 2 0 0 14
18 0 5 4 0 0 20
19 0 4 4 0 0 16
20 0 5 2 0 0 10

Updated on: 04-Jan-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements