[R] fast way to check an object is a member of a list?
Tony Plate
tplate at blackmesacapital.com
Wed Nov 20 19:04:06 CET 2002
if you are talking about atomic objects, is.element() and %in% may do what
you are looking for:
> 5 %in% 1:4
[1] FALSE
> 3 %in% 1:4
[1] TRUE
> is.element(3, as.list(1:4))
[1] TRUE
> is.element(5, as.list(1:4))
[1] FALSE
> 3 %in% as.list(1:4)
[1] TRUE
> 5 %in% as.list(1:4)
[1] FALSE
For general objects (both atomic and non-atomic), I know of no better way
than the one already suggested by John Fox:
> LIST <- as.list(1:4)
> X <- as.integer(3)
> any(sapply(LIST, function(y,x) identical(y,x), X))
[1] TRUE
>
The main problem with using identical() is that it is sensitive to the
storage modes, which can lead to unexpected non-matches:
> LIST <- as.list(1:4) # elements are integer
> X <- 3 # a double value
> any(sapply(LIST, function(y,x) identical(y,x), X))
[1] FALSE
> identical(X, LIST[[3]])
[1] FALSE
> X==LIST[[3]]
[1] TRUE
> storage.mode(X)
[1] "double"
> storage.mode(LIST[[3]])
[1] "integer"
>
hope this helps,
tony plate
At 01:38 PM 11/19/2002 -0800, Francisco J Molina wrote:
>Is there any fast way to check that an object is a member of a list?
>-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
>r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
>Send "info", "help", or "[un]subscribe"
>(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
>_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
>
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list