[R] Strange behaviour of sapply function.

Enrico Schumann e@ @end|ng |rom enr|co@chum@nn@net
Thu Sep 12 11:49:34 CEST 2019


Quoting bickis using math.usask.ca:

> Here is are a few lines of my R session:
>
>> class(income)
> [1] "integer"
>> class(sapply(1000*income-999,atv,sktaxb,sktax))
> [1] "numeric"
>> class(sapply(1000*income-1001,atv,sktaxb,sktax))
> [1] "list"
>
> Although "income" is a numeric array, and sapply works as expected
> returning an array (the function "atv" returns a single numeric argument),
> if subtract a large enough number from the first argument, the sapply
> function now wants to return a list?   Am I missing something?
>
> I am running version 3.3.2 on Mac OS 10.9.9
>

You have not shown what 'income', 'atv', and so on are; so there is an  
infinity
of possible reasons why you get a list instead of a numeric vector.

One possible reason: what if 'atv' sometimes returns no value at all?

f <- function(x) x[x>0]
str(sapply(1:10, f))
## int [1:10] 1 2 3 4 5 6 7 8 9 10

str(sapply(-5:5, f))
## List of 11
##  $ : int(0)
##  $ : int(0)
##  $ : int(0)
##  $ : int(0)
##  $ : int(0)
##  $ : int(0)
##  $ : int 1
##  $ : int 2
##  $ : int 3
##  $ : int 4
##  $ : int 5

-- 
Enrico Schumann
Lucerne, Switzerland
http://enricoschumann.net



More information about the R-help mailing list