To peform element-wise multiplication in R, you can use “*” operator.
The following method shows how you can do it with syntax.
Method 1: Use * Operator
vector1*vector2
The following example shows how to perform element-wise multiplication in R.
Using * Operator
Suppose we have two vectors and want to perform multiplication between them:
# Declare two vectors
x <- c(78,89,85,74,56)
y <- c(12,13,14,56.21,85)
# Perform element wise multiplication
m <- x*y
# Print multiplication output
print(m)
Output:
[1] 936.00 1157.00 1190.00 4159.54 4760.00
Here the output shows elements-wise multiplication of x and y vector.
# Create data frame
df <- data.frame(Machine_name=c("A","B","C","D","E","F","G","H"),
Pressure=c(12.39,11.25,12.15,13.48,13.78,12.89,12.21,12.58),
Temperature=c(78,89,85,84,81,79,77,85),
Status=c(TRUE,TRUE,FALSE,TRUE,FALSE,FALSE,TRUE,FALSE))
# Declare vector
x <- c(78,89,85,74,71,76,81,83)
# Perform element wise multiplication with dataframe
m <- (df$Pressure)*x
# Display multiplication
print(m)
[1] 966.42 1001.25 1032.75 997.52 978.38 979.64 989.01 1044.14
You can perform element wise multiplication between two dataframe but both dataframe must have same number of elements.
# Create data frame
df1 <- data.frame(Machine_name=c("A","B","C","D","E","F","G","H"),
Pressure1=c(12.39,11.25,12.15,13.48,13.78,12.89,12.21,12.58),
Temperature=c(78,89,85,84,81,79,77,85),
Status=c(TRUE,TRUE,FALSE,TRUE,FALSE,FALSE,TRUE,FALSE))
df2 <- data.frame(Machine_name=c("A","B","C","D","E","F","G","H"),
Pressure2=c(9.6,8.85,7.89,10.24,12.36,11.45,9.47,8.12))
# Perform multiplication
m <- (df1$Pressure1) * (df2$Pressure2)
# Print multiplication
print(m)
Output:
[1] 118.9440 99.5625 95.8635 138.0352 170.3208 147.5905 115.6287 102.1496
Here the output shows multiplication between Pressure1 and Pressure2 column of dataframe df1 and df2 respectively.