Vector Calculations Using Functions in R
1. Function to Add Two Vectors
add_vectors <- function(v1, v2) {
return(v1 + v2)
}
a <- c(2, 4, 6)
b <- c(1, 3, 5)
add_vectors(a, b)
# Output: 3 7 11
2. Function to Subtract Two Vectors
subtract_vectors <- function(v1, v2) {
return(v1 - v2)
}
subtract_vectors(a, b)
# Output: 1 1 1
3. Function to Calculate Dot Product
dot_product <- function(v1, v2) {
return(sum(v1 * v2))
}
dot_product(a, b)
# Output: 44
4. Function to Calculate Vector Magnitude
vector_magnitude <- function(v) {
return(sqrt(sum(v^2)))
}
vector_magnitude(a)
5. Function to Check if Vectors are Equal
check_equal <- function(v1, v2) {
return(all(v1 == v2))
}
check_equal(a, b)