Open In App

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

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 –

Implementation combined with this approach paints a better picture.

Example 1:




# 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:




# 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:




# 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


Article Tags :