R语言 如何逆转给定向量的顺序

R语言 如何逆转给定向量的顺序

在这篇文章中,我们将讨论如何在R编程语言中逆转向量中元素的顺序。

这可以用 rev() 函数来完成。它返回数据对象的反向版本。

语法: rev(x)

参数: x。数据对象

返回: 传递的数据对象的反转

例1: 这里我们将创建一个向量,并用rev()函数将其反转。

# create vector with names
vec = c("sravan", "mohan", "sudheer",
         "radha", "vani", "mohan")
  
print("Original vector-1:")
print(vec)
rv = rev(vec)
  
print("The said vector in reverse order:")
print(rv)
Bash

输出

[1] Original vector-1:”

[1] sravan  mohan   sudheer radha   vani    mohan

[1] The said vector in reverse order:”

[1] mohan   vani    radha   sudheer mohan   sravan
Bash

例2: 这里我们将创建多个向量,然后将它们倒置。

# create vector with names
name = c("sravan", "mohan", "sudheer",
         "radha", "vani", "mohan")
  
# create vector with subjects
subjects = c(".net", "Python", "java", 
             "dbms", "os", "dbms")
  
# create a vector with marks
marks = c(98, 97, 89, 90, 87, 90)
  
# create vector with height
height = c(5.97, 6.11, 5.89,
           5.45, 5.78, 6.0)
  
# create vector with weight
weight = c(67, 65, 78,
           65, 81, 76)
  
# pass these vectors to the vector
data = c(name, subjects, marks,
         height, weight)
# display
print("Original vector-1:")
print(data)
rv = rev(data)
  
print("The said vector in reverse order:")
print(rv)
Bash

输出

[1] Original vector-1:”

[1] sravan  mohan   sudheer radha   vani    mohan   “.net

[8] Python  java    dbms    os      dbms    98      97

[15] 89      90      87      90      5.97    6.11    5.89

[22] 5.45    5.78    6       67      65      78      65

[29] 81      76

[1] The said vector in reverse order:”

[1] 76      81      65      78      65      67      6

[8] 5.78    5.45    5.89    6.11    5.97    90      87

[15] 90      89      97      98      dbms    os      dbms

[22] java    Python  “.net    mohan   vani    radha   sudheer

[29] mohan   sravan
Bash

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册