4 Ways to Create a Vector in R

Method 1: Using the c() function

To create a vector in R, the easiest way is to use the “c()” function. The c() function combines its arguments.

rv <- c(11, 46)

print(rv)

Output

[1] 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))

Output

[1] 2

Method 2: Using the : operator

The colon(:) operator helps us create a vector of consecutive numbers.

rv2 <- 1:11

print(rv2)

print(length(rv2))

Output

[1] 1 2 3 4 5 6 7 8 9 10 11
[1] 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))

Output

[1] 1 6 11 16 21
[1] 5

To create a regular sequence vector, you can use the “seq()” function and declare the step size using the by parameter.

Method 3: Using the 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)))

Output

[1] 19 21 11 46

You can see that we created a vector that has four elements using the “assign()” function.

That’s it.

Leave a Comment