20.2 C
London
Sunday, June 22, 2025
HomeRDescriptive Statistics in RHow to Perform Element-Wise Multiplication in R

How to Perform Element-Wise Multiplication in R

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

R is excellent at performing element-wise multiplication between two objects.

The following examples show how to perform element-wise multiplication between various objects in R.

Example 1: Multiply Two Vectors

The following code shows how to perform element-wise multiplication with two vectors:

#create vectors
a #perform element-wise multiplication
a*b

[1]  2  6 12 15

Here is how the results were calculated:

  • 1 * 2 = 2
  • 3 * 2 = 6
  • 4 * 3 = 12
  • 5 * 3 = 15

Example 2: Multiply Data Frame & Vector

The following code shows how to perform element-wise multiplication with a data frame and a vector:

#define data frame
df frame(a=c(1, 3, 4, 5),
                 b=c(2, 2, 3, 3))

#view data frame
df

  a b
1 1 2
2 3 2
3 4 3
4 5 3

#define vector
x #multiply data frame by vector
df*x

   a  b
1  2  4
2 15 10
3 20 15
4 40 24

Example 3: Multiply Two Data Frames

The following code shows how to perform element-wise multiplication between two data frames:

#define data frames
df1 frame(a=c(1, 3, 4, 5),
                  b=c(2, 2, 3, 3))
df2 frame(c=c(6, 2, 2, 2),
                  d=c(1, 7, 4, 9))

#multiply two data frames
df1*df2

   a  b
1  6  2
2  6 14
3  8 12
4 10 27

Note that the resulting data frame is the same size as the two data frames that we multiplied.

Also note that we will receive an error if we attempt to multiply two data frames of different sizes:

#define data frames of unequal sizes
df1 frame(a=c(1, 3, 4, 5),
                  b=c(2, 2, 3, 3))

df2 frame(c=c(6, 2, 2),
                  d=c(1, 7, 4))

#attempt to multiply two data frames
df1*df2

Error in Ops.data.frame(df1, df2) : 
  ‘*’ only defined for equally-sized data frames

Additional Resources

How to Perform Matrix Multiplication in R
How to Convert Matrix to Vector in R
How to Convert Data Frame Column to Vector in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories