[R] Replacing double loop by apply

Andreas Wittmann andreas_wittmann at gmx.de
Fri May 14 14:23:06 CEST 2010


Dear R-users,

after trying and searching a long time i have the following question.
is it possible to replace to following double loop by some apply calls?

#######################################################################

m1 <- data.frame(v1=factor(letters[1:5]),
                 v2=factor(letters[2:6]),
                 v3=factor(letters[3:7]))


m2 <- data.frame(v1=factor(letters[3:7]),
                 v2=factor(letters[1:5]),
                 v3=factor(letters[4:8]))


ind <- matrix(logical(nrow(m2) * ncol(m2)), 
              nrow = nrow(m2), byrow = TRUE)

for (j in 1:ncol(m2)) 
{
  for (i in 1:nrow(m2)) 
  {
    ind[i, j] <- any(levels(m1[, j]) == m2[i, j])
  }
  ind[is.na(ind[, j]), j] <- TRUE
  m2[!ind[, j], j] <- NA
}

#######################################################################




thanks and best regards

Andreas
-- 
GRATIS für alle GMX-Mitglieder: Die maxdome Movie-FLAT!



More information about the R-help mailing list