R:删除向量的最后一个元素

发布于 2024-09-19 21:43:08 字数 62 浏览 3 评论 0原文

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

我知道名称[-元素]符号 但我无法减去完整的部分

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

梦与时光遇 2024-09-26 21:43:09

如果你是单人航班

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

if you're a one liner

x = x[1:(length(x) -101)]
小女人ら 2024-09-26 21:43:09

为了完整起见,另一行话:

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

Another one-liner for the sake of completeness:

x <- lag(x, 100)[-1:-100]
醉酒的小男人 2024-09-26 21:43:08

我喜欢使用 head 来实现此目的,因为它更容易输入。其他方法可能执行得更快...但我很懒,而我的计算机却不是。 ;-)

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

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
时光匆匆的小流年 2024-09-26 21:43:08

实际上,还有一种更快的方法:

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

代码显示:

> 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

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
扎心 2024-09-26 21:43:08

我敢打赌 length<- 是修剪向量的最有效方法:

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

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
对你再特殊 2024-09-26 21:43:08

只需使用数字索引,即

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

您需要确保 N 大于 100 等

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文