Skip to content
Prev 273477 / 398506 Next

Vector-subsetting with ZERO - Is behavior changeable?

You can use [1] on the output of FUN to ensure that
exactly one value (perhaps NA from numeric(0)[1]) is
returned.  E.g.

  > index <- 1
  > sapply(list(c(1,2,3),c(1,2),c(1)),function(x){x[max(length(x)-index,0)][1]})
  [1]  2  1 NA

I'll also put in a plug for vapply, which throws an
error if FUN does not return what you expect it to:

  > vapply(list(c(1,2,3),c(1,2),c(1)),function(x){x[max(length(x)-index,0)]}, FUN.VALUE=numeric(1))
  Error in vapply(list(c(1, 2, 3), c(1, 2), c(1)), function(x) { : 
    values must be length 1,
   but FUN(X[[3]]) result is length 0
  > vapply(list(c(1,2,3),c(1,2),c(1)),function(x){x[max(length(x)-index,0)][1]}, FUN.VALUE=numeric(1))
  [1]  2  1 NA

For long input vectors vapply can save a fair bit of
memory and time over sapply.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com