[R] Skip loop combination when one factor's level is missing
Uwe Ligges
ligges at statistik.tu-dortmund.de
Tue Jun 30 13:49:29 CEST 2009
You can use "drop=TRUE" as argument in indexing (brackets) to drop
unused levels, see the following example:
a <- factor(1:2, levels=1:3)
a
# [1] 1 2
# Levels: 1 2 3
for(i in levels(a)) print(i)
#[1] "1"
#[1] "2"
#[1] "3"
for(i in levels(a[, drop=TRUE])) print(i)
#[1] "1"
#[1] "2"
Uwe Ligges
Paulo E. Cardoso wrote:
> Hi,
>
>
>
> In a symmetric design one may have a data.frame with, say, two factors (two
> columns), each one with n levels.
>
>
>
> In a nested loop, to run a expression combining levels of each factors, to
> produce a new data.frame, if one level is absent, the loop is interrupted;
> one gets a empty object.
>
>
>
> Is there a way to avoid or skip combinations of factors in such nested
> loops?
>
>
>
> I think that the approach below is a very crude example:
>
>
>
> for(i in unique(DF$ID1)) #! For each ID1 level
>
> {
>
> for (e in unique(DF$ID2)) #! For each ID2 level
>
> {
>
> DF.N <- DF[DF$ID1==i & DF$ID2==e,]
>
> if(nrow(DF.N)==0) DF2 <- ??
>
> else
>
>
>
>
>
> Any idea will be welcome
>
>
>
> Paulo
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list