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 <-
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.