[R] mapply instead for loop

Uwe Ligges ligges at statistik.tu-dortmund.de
Sat Nov 3 16:32:12 CET 2012



On 30.10.2012 20:01, Omphalodes Verna wrote:
> Hi all!
>
> My question in about using mapply instead for loop. Below is a example with for loop: Is it posible to give same results with mapply function?
>
> Thanks for help!
>
> OV
>
> x <- 1:10
> y <- 1:10
> xyz <- data.frame(expand.grid(x,y)[1], expand.grid(x,y)[2], z = rnorm(100))
> names(xyz) <- c("x", "y", "z")
> head(xyz)
> size <- 2
> output <- NULL
>
> ### for loop
>
> for(i in 1:dim(xyz)[1]){
> x0 <- xyz[i, "x"]
> y0 <- xyz[i, "y"]
> xyzSel <- xyz[xyz$x >= (x0 - size) & xyz$x < (x0 + size) & xyz$y >= (y0 - size) & xyz$y < (y0 + size), ]
> output[i] <- min(xyzSel$z)
> }
> output

Yes:

output <- mapply(function(x0, y0)
     min(xyz[(xyz$x >= (x0 - size) & xyz$x < (x0 + size)) & (xyz$y >= 
(y0 - size) & xyz$y < (y0 + size)), "z"]),
     xyz$x, xyz$y)

Uwe Ligges



> 	[[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