I don't really get the FUN.VALUE
argument in vapply
.
Here is my example:
a = list(list(1,2), list(1), list(1,2,3))
# give the lengths of each list in a
sapply(a, length)
Now, I try to make it type-safe using vapply
instead of sapply
# gives me same result as sapply
vapply(a, length, FUN.VALUE=1)
# same result, but why?
vapply(a, length, FUN.VALUE=1000)
# gives me error
vapply(a, length, FUN.VALUE="integer")
# gives me error
vapply(a, length, FUN.VALUE="vector")
# gives me error
vapply(a, length, FUN.VALUE=c(1,2))
From ?vapply
I read that FUN.VALUE
can be a scalar, vector or matrix, and is used to match the type of the output. Any hints for why vapply
behaves this way?
From the vapply
documentation,
FUN.VALUE
(generalized) vector; a template for the return value from FUN. See ‘Details’.
Notice that it says "a template for the return value", not "a character string describing the return value". Looking in the Details section provides more guidance:
This function checks that all values of
FUN
are compatible with theFUN.VALUE
, in that they must have the same length and type. [Emphasis added]
The function in your example, length()
returns a numeric of length 1, (an integer, if we want to be specific). When you use FUN.VALUE = 1
, 1
has the same length and type as the output you expect, so the check passes. When you use FUN.VALUE = "integer"
, "integer"
is a character vector of length 1, so the length check passes but the type check fails.
It continues:
(Types may be promoted to a higher type within the ordering logical < integer < double < complex, but not demoted.)
So, if you were vapply
ing a function that might return a value that is integer or double, you should make sure to specify something like FUN.VALUE = 1.0
The documentation continues to talk about how arrays/matrices are handled. I won't copy/paste it here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With