How to Perform Element-Wise Multiplication in R


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 <- c(1, 3, 4, 5)
b <- c(2, 2, 3, 3)

#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 <- data.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 <- c(2, 5, 5, 8)

#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 <- data.frame(a=c(1, 3, 4, 5),
                  b=c(2, 2, 3, 3))
df2 <- data.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 <- data.frame(a=c(1, 3, 4, 5),
                  b=c(2, 2, 3, 3))

df2 <- data.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

Leave a Reply

Your email address will not be published. Required fields are marked *