如何在 R 中反转一个向量?


有时候向量值在 R 中以相反顺序记录下来,因此,我们需要再反转这些向量以获得想要的实际顺序。例如,一系列数字可能以 1-20 的顺序记录,但我们希望它以 20-1 的顺序记录。利用 rev 函数可以轻松完成反转向量的顺序。

示例

x1<-1:20
x1
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
rev(x1)
[1] 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
x2<-letters[1:26]
x2
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"
rev(x2)
[1] "z" "y" "x" "w" "v" "u" "t" "s" "r" "q" "p" "o" "n" "m" "l" "k" "j" "i" "h"
[20] "g" "f" "e" "d" "c" "b" "a"
x3<-LETTERS[1:26]
x3
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T" "U" "V" "W" "X" "Y" "Z"
rev(x3)
[1] "Z" "Y" "X" "W" "V" "U" "T" "S" "R" "Q" "P" "O" "N" "M" "L" "K" "J" "I" "H"
[20] "G" "F" "E" "D" "C" "B" "A"
x4<-rep(c(1,2,3),each=10)
x4
[1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3
rev(x4)
[1] 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
x5<-c("USA","Canada","United Kingdom","Australia","New Zealand")
x5
[1] "USA" "Canada" "United Kingdom" "Australia"
[5] "New Zealand"
rev(x5)
[1] "New Zealand" "Australia" "United Kingdom" "Canada"
[5] "USA"
x6<-c("Name10","Name9","Name8","Name7","Name6","Name5","Name4","Name3","Name2","Name1")
x6
[1] "Name10" "Name9" "Name8" "Name7" "Name6" "Name5" "Name4" "Name3"
[9] "Name2" "Name1"
rev(x6)
[1] "Name1" "Name2" "Name3" "Name4" "Name5" "Name6" "Name7" "Name8"
[9] "Name9" "Name10"
x7<-c(TRUE,FALSE,TRUE,TRUE,FALSE,FALSE,FALSE,FALSE,TRUE,TRUE,FALSE,TRUE,TRUE)
x7
[1] TRUE FALSE TRUE TRUE FALSE FALSE FALSE FALSE TRUE TRUE FALSE TRUE
[13] TRUE
rev(x7)
[1] TRUE TRUE FALSE TRUE TRUE FALSE FALSE FALSE FALSE TRUE TRUE FALSE
[13] TRUE
x8<-c(14,78,25,17,12,19,17,35,26,17,84,45,14,23,52,7,2,19,18,25,65,74,78)
x8
[1] 14 78 25 17 12 19 17 35 26 17 84 45 14 23 52 7 2 19 18 25 65 74 78
rev(x8)
[1] 78 74 65 25 18 19 2 7 52 23 14 45 84 17 26 35 17 19 12 17 25 78 14
x9<-c(1.05,3.21,10.4,7.01,5.02,3.6,5.01,8.2,5.9,4.3,4.58,1.57,2.48)
x9
[1] 1.05 3.21 10.40 7.01 5.02 3.60 5.01 8.20 5.90 4.30 4.58 1.57
[13] 2.48
rev(x9)
[1] 2.48 1.57 4.58 4.30 5.90 8.20 5.01 3.60 5.02 7.01 10.40 3.21
[13] 1.05
x10<-c(5,NA,25,36,TRUE,17,"",65,18,"Class")
x10
[1] "5" NA "25" "36" "TRUE" "17" "" "65" "18"
[10] "Class"
rev(x10)
[1] "Class" "18" "65" "" "17" "TRUE" "36" "25" NA
[10] "5"

更新于:2020 年 8 月 21 日

677 次浏览

开启你的职业生涯

通过完成课程获得认证

开始
广告