Vector Arithmetic in R: Made Easy 2024

The post is about vector arithmetic in R Language. In R, different mathematical operations can be performed on vectors, that is vectors can be used in arithmetic expressions. The vector arithmetic operations are performed element by element.

It is important to note that vectors occurring in the same mathematical expression need not be of the same length (size). The shorter vectors in the arithmetic expression are recycled until they match the length of the longest vector.

Vector Arithmetic Operations

The vector arithmetic operations can be performed using arithmetic operators and vector functions. The +, -, *, /, and ^ are elementary arithmetic operators. The arithmetic functions are also available, such as, log, exp, sin, cos, tan, sqrt, and so on. The max() and min() functions returns the largest and smallest elements of a vector, respectively. Similarly, the range() function results in a vector of length two having minimum and maximum values from the vector, that is, c(min(x), max(x)).

The length(x) function returns the number of elements (size or number of observations) in a vector say $x$, sum(x) gives the total (sum) of the elements in vector $x$, and prod(x) returns the product of elements.

Instead of performing simple arithmetics (+, -, *, and /), we will use some functions for arithmetic that can be performed on a vector.

Vector Arithmetic in R: Examples

The basic vector arithmetic in R can be performed just like adding numbers on a calculator.

x <- c(1, 2, 3, 4, 5)
y <- c(4, 5, 6, 7, 8)

# Addition
x + y

# Subtraction
x - y

# Multiplication
x * y

# Division
x / y

# Exponentiation
x ^ y

One can compute the average (mean value) of a vector by performing arithmetics on a vector, such as

x <- c(5, 10, 5, 3, 5, 6, 7, 8, 4, 3, 10)
sum(x)/ length(x)

## Output
6

The built-in function for the computation of the average value of a vector is mean(), that is mean(x).

mean(x)

## output
6

The variance can also be computed by performing arithmetics on a vector say $x$.

sum((x - mean(x))^2)/ (length(x)-1)

## Output
6.2
Vector Arithmetic in R Language

The built-in function for sample variance is var(x). Note that if the argument var() is a $n$-by-$p$ matrix, a $p$-by-$p$ matrix of the sample covariance matrix will return.

var(x)

## Output
6.2

The sort(x) function returns a vector of the same size as $x$ with the elements arranged in increasing order.

sort(x)

## Output
[1]  3  3  4  5  5  5  6  7  8 10 10

The min() and max() functions are used to select the smallest and largest values from the argument, even if the argument contains several vectors.

In summary, Vector arithmetic is a fundamental aspect of R programming, enabling efficient and concise mathematical operations on sequences of elements. By understanding the basic operations, vector recycling, and available functions, you can effectively leverage vectors to solve a wide range of problems in data analysis and scientific computing.

https://rfaqs.com vector arithme5ics

https://itfeature.com, https://gmstat.com

Matrix Multiplication in R: A Quick Tutorial

Introduction Matrix Multiplication in R

Matrix multiplication is a fundamental operation in linear algebra, and R provides efficient functions. The matrix multiplication in R can be done easily. For this purpose, the %*% operator is used for general matrix multiplication. An $n\times 1$ or $1 \times n$ vector (also called matrix) may be used as an $ n$ vector. In other words, vectors that occur in matrix multiplication expressions are automatically promoted to row (or column) vectors, whichever is multiplicatively coherent, if possible.

Scalar Multiplication

The * operator may be used for multiplying a matrix by a scalar quantity. The scalar value is multiplied by each element of the matrix.

m <- matrix(1:9, nrow = 3)
m <- 2 * m
m
Matrix Multiplication in R

From the above output, it can be seen that each element of the original matrix is multiplied by 2.

Element-wise Multiplication

If $A$ and $B$ are two square matrices of the same size, then the element-wise multiplication between matrices $A$ and $B$ can be performed using the * operator. In element-wise multiplication of the matrices, the corresponding elements of both matrices will be multiplied (provided that the matrices have the same dimension).

A <- matrix(1:9, nrow = 3)
A
## Ouput
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

B <- matrix(10:18, nrow = 3)
B

## Output
     [,1] [,2] [,3]
[1,]   10   13   16
[2,]   11   14   17
[3,]   12   15   18

A * B

## Output
     [,1] [,2] [,3]
[1,]   10   52  112
[2,]   22   70  136
[3,]   36   90  162

Matrix Multiplication in R

The matrix multiplication in R can be done easily. The general multiplication of matrices (matrix product) can be performed using the %*% operator. The matrix multiplication must satisfy the condition that the number of columns in the first matrix is equal to the number of rows in the second matrix. Suppose, if matrix $A$ has $m$ rows and $n$ columns and matrix $B$ has $n$ rows and $x$ columns, then the multiplication of these matrices will result in with dimension of $n times x$. Consider the following example of matrix multiplication in R language.

A <- matrix(1:9, nrow = 3)
B <- matrix(10:18, nrow = 3)

A %*% B
Matrix multiplication in R Language

Note the difference in output between A*B and A%*%B.

Suppose, $x$ is a vector, then the quadratic form of the matrices is

x <- c(5, 6, 7)
A <- matrix(1:9, nrow = 3)
x %% A %% x

## Output
     [,1]
[1,] 1764

Splitting the above multiplication procedure, one can easily understand how the matrices and vectors are multiplied.

x%*%A
## Output
[,1] [,2] [,3]
[1,]   38   92  146

x%*%A%*%x
## Output
     [,1]
[1,] 1764

The crossprod() in R

The function crossprod() forms “crossproducts” meaning that crossprod(X, y) is the same as t(X) %*% y. The crossprod() operation is more efficient than the t(X) %*%y.

crossprod(x, A)
     [,1] [,2] [,3]
[1,]   38   92  146

The cross product of $x$, $A$, the` (crossprod(x, A)) is equivalent to x%*%A, and crossprod(x%*%A, x) is equivalent to x%*%A%*%x.

Multiplication of Large Matrices

For larger matrices, the Matrix package may be used for optimized performance. The Matrix package also helps for working with sparse matrices or matrices with special structures.

Some Important Points about Matrices

  • Be careful about matrix dimensions to avoid errors.
  • Be careful about the use of operators * and %*%.
  • Be careful about the order of the matrices during multiplication (A%*%B, or B%*%A).
  • Explore other matrix operations like addition, subtraction, and transposition using R functions.
  • The dim() function helps identify the dimensions of a matrix.
  • For larger matrices, consider using the solve() function for matrix inversion or the eigen() function for eigenvalue decomposition.
Frequently Asked Questions About R

https://itfeature.com

https://gmstat.com

Vector in R Language

A vector in R is a set of numbers. A vector can be considered as a single column or a single row of a spreadsheet. The following examples are numbers that are not technically “vectors”. It is because these vectors are not in a column/row structure, however, they are ordered. These vectors can be referred to by index.

Creating Vector in R

# Creating a vector with the c function

c(1, 4, 6, 7, 9)

c(1:5, 10)
Creating Vector in R Language

A vector in R language can be created using seq() function, it generates a series of numbers.

# Create a vector using seq() function

seq(1, 10, by = 2)
seq(0, 50, length = 11)
seq(1, 50, length = 11)
Creating Vector in R using seq() Function

The vector can be created in R using the colon (:) operator. Following are the examples

# Create vector using : operator

1:10

## Output
[1]  1  2  3  4  5  6  7  8  9 10

5:1

## Output
[1] 5 4 3 2 1

The non-integer sequences can also be created in R Language.

# non-integer sequences
seq(0, 100*pi, by = pi)
Non integer vector in R

One can assign a vector to a variable using the assignment operator (<-) or equal symbol (=). The examples are:

a <- 1:5
b <- seq(15, 3, length=5)
c <- a * b

There are a lot of built-in functions that can be used to perform different computations on vectors. For example,

a <- 1:5

# compute the total of elements of a vector
sum(a)

## Output
15

# product of elements of a vector
prod(a)

## Output
120

# average of the vector
mean(a)

## Output
3

# standard deviation and variance of a vector
sd(a)

## Output 
1.581139

var(a)

## Output
2.5

One can extract the elements of a vector by using square brackets and the index of the component of the vector.

V <- seq(0, 100, by = 10)
V[] # gives all the elements of the vector

## Output
[1]   0  10  20  30  40  50  60  70  80  90 100

V[5] # 5th elements from vector z

## Output
[1] 40

V[c(2, 4, 6, 8)] #2nd, 4th, th, and 8th element

## Output
[1] 10 30 50 70

V[-c(2, 4, 6, 8)] # elements except 2nd, 4th, 6th, and 8th element

## Output
[1]   0  20  40  60  80  90 100

The specific / required elements of a vector can be updated

V[c(2, 4)] <- c(500, 600) # the second and 4th element is updated to 500 and 600
Updating vector elements in R

https://itfeature.com

https://gmstat.com

The important points about vectors in R language are:

  • Data Types: Vectors can hold logical, integer, double, character, complex, or raw data.
  • Creation: Use the c() function to combine elements into a vector.
  • Accessing Elements: Use indexing (square brackets) to access individual elements.
  • Vector Operations: Perform arithmetic, logical, and comparison operations on vectors.
  • Vectorization: R excels at vectorized operations, making calculations efficient.