Open In App

How to Create a vector of specific type and length in R ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to create a vector of specified type and length in R programming language. To create a vector of specified data type and length in R we make use of function vector(). vector() function is also used to create empty vector.

Syntax:

vector(class of the data object, length of the vector)

There is a very straightforward approach for this.

Steps –

  • Create vector of required type
  • Also pass the size to it
  • Here we can also check the type and size of the vector so created

Implementation combined with this approach paints a better picture.

Example 1:

R




# Create a vector of type integer, numeric class and length 5
a <- vector( "integer" , 5 )
b <- vector( "numeric" , 5 )
  
# Printing vector a
print(a)
  
# Printing the data type of the vector 
print(typeof(a))
  
# Printing the length of vector a
print(length(a))
  
# Printing vector b
print(b)
  
# Printing the data type of the vector b
print(typeof(b))
  
# Printing the length of vector b
print(length(b))


Output:

[1] 0 0 0 0 0

[1] “integer”

[1] 5

[1] 0 0 0 0 0

[1] “double”

[1] 5

Example 2:

R




# Create a vector of type logical and length 5
a <- vector( "logical" , 5 )
  
# Printing vector a
print(a)
  
# Printing the data type of the vector 
print(typeof(a))
  
# Printing the length of vector a
print(length(a))


Output:

[1] FALSE FALSE FALSE FALSE FALSE

[1] “logical”

[1] 5

Example 3:

R




# Create a vector of type character and length 5
a <- vector( "character" , 5 )
  
# Printing vector a
print(a)
  
# Printing the data type of the vector 
print(typeof(a))
  
# Printing the length of vector a
print(length(a))


Output:

[1] “” “” “” “” “”

[1] “character”

[1] 5



Last Updated : 05 Apr, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads