如何在 R 中创建特定类型和长度的向量?
在本文中,我们将看到如何在 R 编程语言中创建指定类型和长度的向量。为了在 R 中创建指定数据类型和长度的向量,我们使用函数vector()。 vector()函数也用于创建空向量。
句法:
vector(class of the data object, length of the vector)
对此有一个非常直接的方法。
脚步 -
- 创建所需类型的向量
- 还将大小传递给它
- 在这里我们还可以检查这样创建的向量的类型和大小
与这种方法相结合的实施描绘了一幅更好的画面。
示例 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))
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))
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))
输出:
[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