R 程序:创建一个向量并查找其长度和维度


2023 年 2 月 25 日, Learn eTutorial
1678

如何使用 R 程序创建一个向量并查找其长度和维度?

要编写一个 R 程序来创建向量并计算其长度和维度,我们使用内置函数 dim()length()

  • dim() 用于检索或设置对象的维度。
  • length() 用于获取或设置向量(包括列表)和因子以及任何其他 R 对象的长度。

它们的语法是:

dim(x)
length(x) 
 
  • x 是一个 R 对象,例如矩阵、数组或数据框。

在这个 R 程序中,我们直接将值赋给内置函数,在此之前我们显示向量值。然后,我们考虑变量 A,其中分配了向量值。调用函数 dim() 用于查找维度,调用 length() 用于查找向量的长度。最后,打印结果。

算法

步骤 1: 将向量值赋给变量 A

步骤 2: 显示实际的向量值

步骤 3: 调用函数 dim(),例如 dim(A)

步骤 4: 打印函数的结果

步骤 5: 调用函数 length(),例如 length(A)

步骤 6: 打印函数的结果

 

R 源代码

                                          A = c(1,3,5,7,9,6)
print("Original vectors is:")
print(A)
print("Dimension of the vector is:")
print(dim(A))
print("length of the vector is:")
print(length(A))
                                      

输出

[1] "Original vectors is:"
[1] 1 3 5 7 9 6
[1] "Dimension of the vector is:"
NULL
[1] "length of the vector is:"
[1] 6