[R] repeated %in%

Peter Dalgaard p.dalgaard at biostat.ku.dk
Fri Nov 18 11:35:17 CET 2005


Robin Hankin <r.hankin at noc.soton.ac.uk> writes:

> Hi
> 
> I have a list of vectors, each one of which should be a subset of the  
> previous one.
> How do I check that this property actually holds?
> 
> Toy problem follows with a list of length 4 but my list can be any  
> length
> 
> 
> subsets <- list(
>                  l1 = 1:10 ,
>                  l2 = seq(from=1,to=9,by=2),
>                  l3 = c(3,7),
>                  l4 = 3
>                  )
> 
> I need
> 
> all(subsets[[4]] %in% subsets[[3]]) &
> all(subsets[[3]] %in% subsets[[2]]) &
> all(subsets[[2]] %in% subsets[[1]])
> 
> I can write a little function to do this:
> 
> 
> check.for.inclusion <- function(subsets){
>    out <- rep(FALSE,length(subsets)-1)
>    for(i in 1:(length(subsets)-1)){
>      out[i] <- all(subsets[[i+1]] %in% subsets[[i]])
>    }
>    return(all(out))
> }
> 
> 
> how to do it elegantly and/or quickly?

How about

> !any(sapply(mapply(setdiff,subsets[-1],subsets[-4]),length))
[1] TRUE

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907




More information about the R-help mailing list