[R-sig-Geo] for loop with kde (ks package) function not working

Forrest Stevens forrest at ufl.edu
Mon Mar 4 06:50:31 CET 2013


> I am trying to run a for loop 1000 times to randomly sample spatial points
...
> different values). However, when I look at the results from the kde function
> the first two outputs are different and then each iteration after that just
> produces the exact same values.

Hi Kathryn, I believe the problem you're facing is that you are
setting the random seed each time through your loop, which effectively
resets the random number generation to the same point, and therefore
duplicates your random sample each time.  The key is to move the
set.seed() call outside your for() loop.

Hopefully that solves it for you,
Forrest

> Code:
>
> library(ks)
>
> setwd("/Users/kalee/Documents/Feb 2013/")
> set.seed(8192)
>
> for (i in 1:5 ) {
>
> x <- sample(-300:250, 100, replace = TRUE)
> y <- sample(-30:50, 100, replace = TRUE)
>
> xy <- cbind(x, y)
>
> ID <- sample(1:22, 100, replace = TRUE)
>
>
> dat <- as.data.frame(cbind(ID, xy))
>
>
> dat$X2 <- jitter(dat$x)
> dat$Y2 <- jitter(dat$y)
>
>
>
> idh <- split(dat, list(dat$ID), drop = TRUE)
> y <- lapply(idh, "[", c('X2','Y2'))
> x <- Filter(function (t) nrow(unique(t)) > 5, y)
>
> myfun1<- function(x, k) {
>      H.s <- Hpi(x[[k]], binned = TRUE)
>      KDE <- kde(x[[k]], H=H.s, binned = TRUE)
>      cont <- contourSizes(KDE, cont = c(95), approx = TRUE)
>      return(cont)
>   }
>
>
>   results95 <- rep(0, length(unique(x)))
>   for (j in 1:length(results95)) results95[j] <- myfun1(x, j)
>
>   z <- as.matrix(x)
>   m <- dimnames(z)
>   l <-list(m[[1]], results95)
>
>   write.csv(l, file = paste("blues_function test",i,".csv"))
> }

-- 
Ph.D. Candidate, QSE3 IGERT Fellow
Department of Geography
Land Use and Environmental Change Institute
University of Florida
www.clas.ufl.edu/users/forrest



More information about the R-sig-Geo mailing list