R: removing the last elements of a vector

RVectorElements

R Problem Overview


How can I remove the last 100 elements of a zoo series?

I know the name[-element] notation but I can't get it work to substract a full section

R Solutions


Solution 1 - R

I like using head for this because it's easier to type. The other methods probably execute faster though... but I'm lazy and my computer is not. ;-)

x <- head(x,-100)
> head(1:102,-100)
[1] 1 2

Solution 2 - R

Actually, there's a much faster way:

y <- x[1:(length(x)-1)]

Code show:

> microbenchmark( y <- head(x, -1), y <- x[-length(x)],y <- x[1:(length(x)-1)], times=10000)
 Unit: microseconds
                      expr    min      lq     mean  median      uq      max
          y <- head(x, -1) 71.399 76.4090 85.97572 78.9230 84.2775 2795.076
        y <- x[-length(x)] 53.623 55.5585 65.15008 56.5680 61.1585 2523.141
 y <- x[1:(length(x) - 1)] 25.722 28.2925 36.43029 29.1855 30.4010 2410.975

Solution 3 - R

I bet length<- is the most efficient way to trim a vector:

> x <- 1:10^5
> length(x)
[1] 100000
> length(x) <- 3
> x
[1] 1 2 3

Solution 4 - R

Just use the numeric indices, ie

 N <- nrow(X)
 X <- X[1:(N-100-1),]

where you should need to ensure N is larger 100 etc

Solution 5 - R

if you're a one liner

x = x[1:(length(x) -101)]

Solution 6 - R

Another one-liner for the sake of completeness:

x <- lag(x, 100)[-1:-100]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionskanView Question on Stackoverflow
Solution 1 - RJoshua UlrichView Answer on Stackoverflow
Solution 2 - RQinsiView Answer on Stackoverflow
Solution 3 - RKen WilliamsView Answer on Stackoverflow
Solution 4 - RDirk EddelbuettelView Answer on Stackoverflow
Solution 5 - RArthur RizzoView Answer on Stackoverflow
Solution 6 - RStewbacaView Answer on Stackoverflow