The intersection function returns a different mode depending on the order of input

Probably the real question is, "Should anyone care", but here's the inconsistency:

intersect(c(),1:3)
integer(0)
intersect(1:3,c())
NULL

      

The same happens with setdiff

, but it makes sense because it is setdiff

designed to be asymmetrical with respect to its two inputs. Now it is more or less obvious from the source for intersect

why this is happening, since the algorithm is asymmetric, although the intersection of the two sets is symmetric.

The question, I think, is whether this can lead to code corruption when any parent function depends on the output mode.

(Background: I got some requests from the user to correct the current turnaround package:vecsets

in order to properly handle empty inputs, and I would like the result to match the class, mode, etc. of the base functions as closely as possible).

+3


source to share


1 answer


from ?intersect

, it looks like the documentation assumes that a vector of the same "mode" is required. c()

- "NULL". Using as.integer()

to change the class c()

seems to work.



class(c())
# [1] "NULL"
class(1:3)
# [1] "integer"
class(as.integer(c()))
# [1] "integer"
intersect(c(1:3), as.integer(c()))
# integer(0)
intersect(as.integer(c()), c(1:3))
# integer(0)

      

+3


source







All Articles