Efficient way to remove first and last elements of a vector

Three different ways to remove first and last elements of a vector are compared. The winner is without contest: v[-c(1, length(v))]

> v <- 1:100
> head(v[-1], -1)
 [1]  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
[30] 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
[59] 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
[88] 89 90 91 92 93 94 95 96 97 98 99
> rev(rev(v[-1])[-1])
 [1]  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
[30] 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
[59] 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
[88] 89 90 91 92 93 94 95 96 97 98 99
> v[-c(1, length(v))]
 [1]  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
[30] 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
[59] 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
[88] 89 90 91 92 93 94 95 96 97 98 99

> system.time(for(i in 1:100000) head(v[-1], -1))
utilisateur     système      écoulé
      2.427       0.072       2.502
> system.time(for(i in 1:100000) rev(rev(v[-1])[-1]))
utilisateur     système      écoulé
      2.157       0.203       2.422
> system.time(for(i in 1:100000) v[-c(1, length(v))])
utilisateur     système      écoulé
      0.329       0.039       0.368

Commentaires

Posts les plus consultés de ce blog

Standard error from Hessian Matrix... what can be done when problem occurs

stepAIC from package MASS with AICc

Install treemix in ubuntu 20.04