R语言 如何创建一个特定类型和长度的向量
在这篇文章中,我们将看到如何在R编程语言中创建一个指定类型和长度的向量。为了在R语言中创建一个指定数据类型和长度的向量,我们使用函数 vector()。 vector()函数也用于创建空向量。
语法 。
vector(数据对象的类别,向量的长度)
对此有一个非常直接的方法。
步驟 –
- 创建所需类型的向量
- 同时将大小传递给它
- 在这里,我们也可以检查这样创建的向量的类型和大小
实施与这种方法相结合,可以描绘出更好的画面。
例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))
输出 。
[1] 0 0 0 0 0
[1] “integer”
[1] 5
[1] 0 0 0 0 0
[1] “double”
[1] 5
例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))
输出 。
[1] FALSE FALSE FALSE FALSE FALSE
[1] “logical”
[1] 5
例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))
输出 。
[1] “” “” “” “” “”
[1] “character”
[1] 5