salaries <- list(leaders = c(250, 200), assistant = 100, members = c(300, 200, 180, 120, 100))
> vapply(salaries, range, c(min=0, max=0))
leaders assistant members
min 200 100 100
max 250 100 300
In this script, the results are always the same regardless of the min and max values, so I wonder what '=0' means here.
What I've tried.
> vapply(salaries, range, c(min=0.1, max=1))
leaders assistant members
min 200 100 100
max 250 100 300
> vapply(salaries, range, c(min=2, max=1))
leaders assistant members
min 200 100 100
max 250 100 300
> vapply(salaries, range, c(min=1000, max=1000))
leaders assistant members
min 200 100 100
max 250 100 300
Realize what third argument of
vapply
actually means.Consider this
for
loop. To code it efficiently, we pre-allocate memory, i.e. we create an empty numeric arraym
(aka matrix) that we fill up later.m
will have number of rows according to the output of therange
function which is of length2
, and number of columns according to the length of the object we will loop over,length(salaries)
.Since
vapply
automatically detectslength(salaries)
, we only need to specify type and length of the output of therange
function, which is exactly what we're doing in the third argument. How exactly you do that is up to you; you could doc(0, 0)
,c(min=2, max=1)
,rep.int(0, 2)
—I personally usenumeric(length=2L)
(akadouble(.)
) which clarifies best, that a numeric vector of length 2 is wanted.Note, that, since your results will be of type
double
, doingFUN.VALUE=integer(2L)
would fail.Pre-allocation with
vapply
results in a much faster calculation than usingsapply
, which gives the same result but is slower without allocation.Benchmark
To show that this actually makes a difference, here a benchmark of the examples.