remove the last element of a vector

后端 未结 4 597
猫巷女王i
猫巷女王i 2020-12-14 14:29

I need to remove the last number in a groups of vectors, i.e.:

v <- 1:3
v1 <- 4:8

should become:

v <- 1:2
v1 <-         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-14 15:00

    Dirk and Iselzer have already provided the answers. Dirk's is certainly the most straightforward, but on my system at least it is marginally slower, probably because vector subsetting with [ and length checking is cheap (and according to the source, head does use length, twice actually):

    > x <- rnorm(1000)
    > system.time(replicate(50000, y <- head(x, -1)))
       user  system elapsed 
       3.69    0.56    4.25 
    > system.time(replicate(50000, y <- x[-length(x)]))
       user  system elapsed 
      3.504   0.552   4.058
    

    This pattern held up for larger vector lengths and more replications. YMMV. The legibility of head certainly out-weights the marginal performance improvement of [ in most cases.

提交回复
热议问题