Vector operations in R allow you to perform various mathematical and logical operations on vectors. These operations are typically carried out element-wise, meaning the operation is applied to each element of the vectors. Here are some common vector operations in R:
1. Arithmetic Operations:
You can perform basic arithmetic operations like addition, subtraction, multiplication, and division on vectors. The operations are carried out element by element.
vector1 <- c(1, 2, 3, 4, 5)
vector2 <- c(5, 4, 3, 2, 1)
# Addition
result_addition <- vector1 + vector2 # Element-wise addition
# Subtraction
result_subtraction <- vector1 – vector2 # Element-wise subtraction
# Multiplication
result_multiplication <- vector1 * vector2 # Element-wise multiplication
# Division
result_division <- vector1 / vector2 # Element-wise division
2. Element-wise Logical Operations:
You can perform logical operations like AND (&), OR (|), and NOT (!) on logical vectors. These operations are applied element-wise and return logical vectors.
logical_vector1 <- c(TRUE, TRUE, FALSE, FALSE)
logical_vector2 <- c(TRUE, FALSE, TRUE, FALSE)
# Logical AND
result_and <- logical_vector1 & logical_vector2 # Element-wise AND
# Logical OR
result_or <- logical_vector1 | logical_vector2 # Element-wise OR
# Logical NOT
result_not <- !logical_vector1 # Element-wise NOT
3. Comparison Operations:
You can compare vectors element-wise using comparison operators such as <, >, <=, >=, ==, and !=. These operations return logical vectors.
vector1 <- c(1, 2, 3, 4, 5)
vector2 <- c(3, 2, 2, 4, 6)
# Equality
result_equal <- vector1 == vector2 # Element-wise equality check
# Greater than
result_greater_than <- vector1 > vector2 # Element-wise greater than check
4. Other Mathematical Functions:
R provides various mathematical functions that can be applied to vectors element-wise, including sqrt(), exp(), log(), abs(), sin(), cos(), and more.
vector <- c(1, 4, 9, 16, 25)
# Square root
result_sqrt <- sqrt(vector) # Element-wise square root
# Exponential function
result_exp <- exp(vector) # Element-wise exponential
5. Vector Concatenation or combining vectors
You can concatenate vectors using the c() function to create a new vector.
vector1 <- c(1, 2, 3)
vector2 <- c(4, 5, 6)
concatenated_vector <- c(vector1, vector2) # Concatenates the two vectors
These are some of the basic vector operations in R. R provides a rich set of functions and operators to work with vectors, making it a powerful language for data analysis and manipulation.