What are vectors and how to do vector assignment in R?
Vectors
Vectors data structures in R consist of order collection of numbers, characters, or strings. There are two major types of vectors:
- Atomic or homogeneous vectors
- Recursive or heterogeneous vectors.
To create a vector named x, with values namely 10, 20, 30, 3.5 and 3.8, use c() function in R command:
x <- c(10, 20, 30, 3.5, 3.8)
Note: The
c()function will return a vector.
Assignment in R
There are various methods or operators in R to perform assignment operations. Let’s discuss some techniques to perform this operation on vectors.
Using<- operator
This assignment operator(<-) consists of two characters:
<(less than)-(minus)
These two characters occur side by side, while the tip points to a variable will receive an assignment value. The assignment of <- operator is also possible in reverse direction ->.
Example
Let’s look at the code below:
# USING <- OPERATORcat("Arrow assignment: ")x <- c(10, NA, 30, 'shot', 3.8)cat(x, end='\n')# Assignment operator in reverse directionc(10.4, 5.6, 3.1, 6.4, 'AB') -> ycat("Revered arrow assignment: ", y, end='\n')
Explanation
- Line 3: We create a vector using the
c()function and assign it to thexvariable using<-operator. - Line 4: We print the vector
xon console. - Line 6: We create a vector using the
c()function and assign it toyvariable using->reversed operator. - Line 7: We print vector
yto the console.
Using = operator
Equal to (=) operator is also used for value assignment. So, we can perform the above operation like:
x = c(9, 8, 23, 4.5, 9.8)
Example
Let’s understand the equal = operator with the help of a code example:
# USING = OPERATORx = c(10, NA, 30, 'shot', 3.8)cat(x)
Explanation
- Line 2: We create a vector
xusing thec()function and equal to=operator. - Line 3: We print
xto the console.
Using assign()
Assignment can also be made by using the assign() method. It’s an equivalent method of assignment as above.
Example
In the example below, we use the assign() function in detail:
# USING assign() FUNCTIONassign("x", c(10, NA, 30, 'Edpresso', 3.8))cat(x)
Explanation
- Line 2: We use the
assign()function for assignment second argument value to first one. - Line 3: We print the vector
xto the console.