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? -- Robin Hankin Uncertainty Analyst National Oceanography Centre, Southampton European Way, Southampton SO14 3ZH, UK tel 023-8059-7743
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
Robin Hankin wrote:> 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? >My first thought was to rewrite that function but drop out if it didnt match. But then... Assuming the first list element is the longest, then its a one liner: check2 <- function(l){ length(unique(unlist(l))) == length(l[[1]]) } - basically the set of everything in all the elements is the first element, so take unique(everything) and see if its the same size as the first element. Unless I've missed something... I'd call that elegant, it may also be quicker! Baz