To add vectors in R, use the + operator.
In this tutorial, we will not concatenate the vectors; we will perform addition operations on two or more vectors.
If your intention is to concatenate strings from two vectors element-wise, use the paste(), c(), or paste0() function.
Example 1: Adding two vectors
vec1 <- 1:3
cat("The first vector is: ", vec1, "\n")
vec2 <- 4:6
cat("The second vector is: ", vec2, "\n")
vec3 <- vec1 + vec2
cat("The final vector is: ", vec3)
Output
The first vector is: 1 2 3
The second vector is: 4 5 6
The final vector is: 5 7 9
Example 2: Adding two vectors of different lengths
What if two vectors have different lengths?
Well in that case, we will get a warning message: longer object length is not a multiple of shorter object length.
vec1 <- 1:3
cat("The first vector is: ", fv, "\n")
vec2 <- 4:8
cat("The second vector is: ", sv, "\n")
vec3 <- vec1 + vec2
cat("The final vector is: ", add)
Output
The first vector is: 1 2 3
The second vector is: 4 5 6 7 8
Warning message:
In vec1 + vec2 :
longer object length is not a multiple of shorter object length
The final vector is: 5 7 9 8 10
Example 3: Adding three vectors
vec1 <- c(1, 2, 3)
vec2 <- c(4, 5, 6)
vec3 <- c(7, 8, 9)
vec4 <- vec1 + vec2 + vec3
vec4
Output
[1] 12 15 18
Example 4: Adding vectors of different DataTypes
num_vec <- 1:3
cat("The first vector is: ", fv, "\n")
char_vec <- c("Snape", "Minerva", "Horace")
cat("The second vector is: ", sv, "\n")
add <- num_vec + char_vec
cat("The final vector is: ", add)
Output
The first vector is: 1 2 3
The second vector is: Snape Minerva Horace
Error in fv + sv : non-numeric argument to binary operator
Execution halted
Example 4: Adding vectors of character type
vec1 <- rep("Grogu", 3)
cat("The first vector is: ", vec1, "\n")
vec2 <- rep("Grogu", 3)
cat("The second vector is: ", vec2, "\n")
add <- vec1 + vec2
print(add)
cat("The final vector is: ", add)
Output
The first vector is: MJ MJ MJ
The second vector is: MJ MJ MJ
Error in dv + iv : non-numeric argument to binary operator
Execution halted
The + operator is not designed to concatenate or add character strings in R. We get an error because the addition operation (+) is not defined for character vectors.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.