删除向量的最后一个元素。

时间:2021-09-12 12:17:58

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

如何删除动物园系列的最后100个元素?

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

我知道名称[-element]表示法,但我不能让它工作到一个完整的部分。

6 个解决方案

#1


72  

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

#2


8  

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

#3


8  

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

#4


7  

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

你需要确保N大于100等等?

#5


5  

if you're a one liner

如果你是一个班轮。

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

#6


2  

Another one-liner for the sake of completeness:

为了完整性起见,另一个一行程序:

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

#1


72  

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

#2


8  

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

#3


8  

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

#4


7  

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

你需要确保N大于100等等?

#5


5  

if you're a one liner

如果你是一个班轮。

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

#6


2  

Another one-liner for the sake of completeness:

为了完整性起见,另一个一行程序:

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