Vectors and Vector Operations in R
Join our community on Telegram!
Join the biggest community of Pharma students and professionals.
In R, a vector is the most basic and commonly used data structure. A vector is a collection of elements of the same data type, such as numbers, characters, or logical values. Even a single value in R is treated as a vector of length one. Vectors are widely used in data analysis because they allow you to store and process multiple values efficiently.
Vectors are usually created using the c() function, which stands for “combine” or “concatenate.” For example, numbers <- c(10, 20, 30, 40) creates a numeric vector, while names <- c("Amit", "Ravi", "Neha") creates a character vector. All elements inside a vector must be of the same data type. If different types are combined, R automatically converts them into a common type.
Vector operations allow you to perform calculations on all elements at once. This is one of the powerful features of R. Instead of using loops, you can apply arithmetic or logical operations directly to vectors. For example, if x <- c(1, 2, 3) and y <- c(4, 5, 6), then x + y returns 5 7 9. The operation is performed element by element.
Below is a simple table showing common vector operations in R:
| Operation Type | Operator/Function | Example | Result |
|---|---|---|---|
| Addition | + |
c(1,2,3) + c(4,5,6) |
5 7 9 |
| Subtraction | - |
c(5,6,7) - c(1,2,3) |
4 4 4 |
| Multiplication | * |
c(2,3,4) * 2 |
4 6 8 |
| Division | / |
c(10,20,30) / 10 |
1 2 3 |
| Exponent | ^ |
c(2,3,4) ^ 2 |
4 9 16 |
| Comparison | > |
c(2,5,1) > 2 |
FALSE TRUE FALSE |
| Logical AND | & |
c(TRUE,FALSE,TRUE) & c(TRUE,TRUE,FALSE) |
TRUE FALSE FALSE |
| Sequence | : |
1:5 |
1 2 3 4 5 |
| Replication | rep() |
rep(2,3) |
2 2 2 |
Vectors make calculations faster and simpler because operations are applied to all elements at once. Understanding vectors and their operations is essential for working with data in R, as most data manipulation and analysis tasks rely heavily on vector-based computations.
