[R] test for nested factors
Tim Bergsma
timb at metrumrg.com
Mon Jun 4 14:50:07 CEST 2007
Is there a conventional way to test for nested factors? I.e., if 'a'
and 'b' are lists of same-length factors, does each level specified by
'a' correspond to exactly one level specified by 'b'?
The function below seems to suffice, but I'd be happy to know of a more
succinct solution, if it already exists.
Thanks,
Tim.
---
"%nested.in%" <- function(x,f,...){
#coerce to list
if(!is.list(x))x<-list(x)
if(!is.list(f))f<-list(f)
#collapse to vector
x <- tapply(x[[1]],x)
f <- tapply(f[[1]],f)
#analyse
return(all(sapply(lapply(split(f,x),unique),length)==1))
}
CO2$Plant %nested.in% CO2[,c("Type","Treatment")] #TRUE
CO2$Plant %nested.in% (CO2$uptake < mean(CO2$uptake)) #FALSE
More information about the R-help
mailing list