访问给定向量中最后一个值的R程序


2023年2月7日, Learn eTutorial
1923

如何在R编程中访问给定向量中的最后一个值?

为了编写一个R程序来访问给定向量中的最后一个值,我们使用了内置函数 tail()tail() 函数有助于返回数据集的最后 n 行。该方法的语法如下:

tail(x,n=number)

其中,

  • x 是输入数据集/数据框
  • n 是函数应该显示的行数。

在这个R程序中,我们打印原始向量,然后直接将值赋给内置函数。并打印函数结果。这里我们使用变量 A 来赋值向量。

算法

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

步骤2:首先我们显示原始向量值

步骤3:调用函数 tail 为 tail(A,n=1)

步骤 4: 打印函数的结果

 

R 源代码

                                          A= c(32, 40, 12, 23, 27, 38, 9, 17)
print("Original Vectors:")
print(A)
print("Access the last value of the vector:")
print(tail(A, n=1))

                                      

输出

[1] "Original Vectors:"
[1] 32, 40, 12, 23, 27, 38, 9, 17
[1] "Access the last value of the vector:"
[1] 17