Creating a vector is easy, and there are four ways to generate it. Each method creates a vector, but you can use the specific method for specific scenarios. Elements of a vector are called Components.
What is Vector in R?
A vector is a sequence of elements that share the same data type. Vector can hold single or multiple values of a single type.
Vector can contain various data types like integer, double, character, logical, complex, or raw.
Create Vector in R
To create a vector in R, use the c() function. The c() is a built-in function that combines its arguments.
rv <- c(11, 46) print(rv)
 11 46
You can see that we created a vector rv using the c() function. It has two elements, 11 and 46.
To get the length of a vector, use the length() function.
rv <- c(11, 46) print(length(rv))
Creating a vector using the : operator
The colon(:) operator helps us create a vector of consecutive numbers.
rv2 <- 1:11 print(rv2) print(length(rv2))
 1 2 3 4 5 6 7 8 9 10 11  11
Using the colon operator in this example, we created a vector of consecutive numbers.
Create a regular sequence vector using the seq() function
The seq() is a built-in R function that generates the general or regular sequences from the given inputs.
rv3 <- seq(1, 25, by = 5) print(rv3) print(length(rv3))
 1 6 11 16 21  5
To create a regular sequence vector, use the seq() function and declare the step size using the by parameter.
Using assign() function
The assign() is a built-in R function that assigns a value to a name in an environment.
print(assign("rv4", c(19, 21, 11, 46)))
 19 21 11 46
You can see that we created a vector that has four elements using the assign() function.
- The best way to create a vector in R is to use the c() function.
- To create a vector of consecutive numbers, use the : operator.
- To create a vector of regular sequence, use the seq() function.
Krunal Lathiya is an Information Technology Engineer by education and web developer by profession. He has worked with many back-end platforms, including Node.js, PHP, and Python. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language. Krunal has written many programming blogs, which showcases his vast expertise in this field.