[R] Replacing double loop by apply

Henrique Dallazuanna
Fri, 14 May 2010 12:42:08 -0000

Try this:

mapply(function(x, y)x[match(x, y)], m2, m1)

On Fri, May 14, 2010 at 9:23 AM, Andreas Wittmann
<andreas_wittmann@gmx.de>wrote:

> 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!
>
> ______________________________________________
> R-help@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.
>



--
Henrique Dallazuanna
Curitiba-Paraná-Brasil
25° 25' 40" S 49° 16' 22" O

	[[alternative HTML version deleted]]