remove the last element of a vector

后端 未结 4 602
猫巷女王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 14:56

    This is another option, which has not been suggested before. NROW treats your vector as a 1-column matrix.

    v[-max(NROW(v))]#1 2
    v1[-max(NROW(v1))]#4 5 6 7
    

    Based on the discussion above, this is (slightly) faster then all the other methods suggested:

    x <- rnorm(1000)
    system.time(replicate(50000, y <- head(x, -1)))
    user  system elapsed 
    3.446   0.292   3.762
    system.time(replicate(50000, y <- x[-length(x)]))
    user  system elapsed 
    2.131   0.326   2.472
    system.time(replicate(50000, y <- x[-max(NROW(x))]))
    user  system elapsed 
    2.076   0.262   2.342
    

提交回复
热议问题