logo

Calculating the Dot Product of Vectors in R 📂R

Calculating the Dot Product of Vectors in R

Code

x<-1:10; x
y<-(-1)^(1:10); y
 
sum(x*y)
 
x %*% y
x %o% y

When analyzing or simulating in R, it’s common to calculate the weighted average. Of course, mathematically, $\displaystyle \left< \mathbf{x}, \mathbf{y} \right> = \sum_{i=1}^{n} x_{i} y_{i}$ is very simple, and since vector operations in R itself are very convenient, one can easily perform inner products just by using the sum() function. However, this can reduce the readability of the code in the long run.

On the other hand, a $n$ dimensional vector can be considered as a $1 \times n$ dimensional matrix. Using this, simple inner product calculations can be achieved through matrix multiplication. This is neither surprising nor anything special, just a simple reminder.

20190515\_104637.png Another tip is that the binary operation %o% returns the outer product of two vectors.