Syntax error How to multiply corresponding values from two data frames in R?

How to multiply corresponding values from two data frames in R?



To multiply corresponding values from two data frames in R, we can follow the below steps −

  • First of all, create two data frames.

  • Then, use mapply function to multiply corresponding values from those two data frames.

Example

Create the first data frame

Let’s create a data frame as shown below −

df1<-data.frame(x1=rpois(25,2),x2=rpois(25,2))
df1

Output

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

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

Create the second data frame

Let’s create a data frame as shown below −

df2<-data.frame(y1=rpois(25,2),y2=rpois(25,2))
df2

Output

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

Multiply corresponding values from two data frames

Using mapply function to multiply corresponding values in data frames df1 and df2 −

df1<-data.frame(x1=rpois(25,2),x2=rpois(25,2))
df2<-data.frame(y1=rpois(25,2),y2=rpois(25,2))
mapply(`*`,df1,df2)

Output

      x1 x2
[1,]   4  3
[2,]  10  6
[3,]   2  4
[4,]   0  0
[5,]   3  0
[6,]   0 12
[7,]   0  2
[8,]   0  4
[9,]   0  0
[10,]  0  0
[11,]  2  0
[12,] 12  0
[13,]  9  0
[14,]  0  0
[15,]  3 12
[16,]  8  3
[17,]  1  4
[18,]  9 12
[19,]  4  0
[20,]  0  3
[21,]  4  4
[22,]  0 25
[23,]  8  2
[24,]  0  0
[25,]  9  7
Updated on: 2021-11-12T05:46:06+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements