[R] test for nested factors

hadley wickham h.wickham at gmail.com
Mon Jun 4 15:29:09 CEST 2007


On 6/4/07, Tim Bergsma <timb at metrumrg.com> wrote:
> 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.

How about:

"%nested%" <- function(a, b) {
	if (is.list(a)) a <- do.call("interaction", c(a, drop=TRUE))
	if (is.list(b)) b <- do.call("interaction", c(b, drop=TRUE))
	
	length(unique(a))  == length(unique(interaction(a, b, drop=TRUE)))
}

CO2$Plant %nested% CO2[,c("Type","Treatment")] #TRUE
CO2$Plant %nested% (CO2$uptake < mean(CO2$uptake)) #FALSE

?

Hadley



More information about the R-help mailing list