Search code examples
rsapply

R logical(0) in sapply


Why does

sapply(c(TRUE, FALSE, logical(0)), length)

return

[1] 1 1

In other words, how come the logical(0) is ignored?


Solution

  • what @PenelopeHopHop said is true however she didn't explain the error. the error is rising from the c() function combines it's arguments and because logical(0) is empty it doesn't get combined making the input of the sappply of length 2 thus the output is of length 2.

    c(TRUE, FALSE, logical(0))
    #> [1]  TRUE FALSE
    

    What you can be achieved if you replace c() with list()

    list(TRUE, FALSE, logical(0))
    #> [[1]]
    #> [1] TRUE
    #> 
    #> [[2]]
    #> [1] FALSE
    #> 
    #> [[3]]
    #> logical(0)
    sapply(list(TRUE, FALSE, logical(0)), length)
    #> [1] 1 1 0
    

    And instead of using sapply(..., length) use lengths function as it does what you aim to achieve.

    lengths(list(TRUE, FALSE, logical(0)))
    #> [1] 1 1 0