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

kalee kathryn.lee1 at students.mq.edu.au
Mon Mar 4 04:27:43 CET 2013


Hi all,

I am trying to run a for loop 1000 times to randomly sample spatial points
and then pass these coordinates to the kde function in the 'ks' package.
When I look at the output from the random selection of points that code
seems to be working fine (i.e. each iteration of the for loop produces
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. I've posted a simplified example of my code
(simulating data instead of running through the random selection process)
but it produces the same errors when I look at the results. I'm sure I'm
missing something really obvious I'm just not sure where to look. 

Many thanks

Code:

library(ks)

setwd("/Users/kalee/Documents/Feb 2013/")

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


set.seed(8192)
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"))
}

Example of results:

Iteration 1:

1	1	22659.13004
2	2	26688.41093
3	3	19403.62449
4	4	26710.38738
5	9	18968.71687
6	11	31870.62336
7	19	11019.08475
8	22	4163.867828


Iteration 2:

1	3	34613.00041
2	4	32962.57106
3	8	21379.64701
4	12	29499.05166
5	14	12065.95155
6	16	26973.81732
7	18	23929.58449

Iteration 3 onwards:

1	3	34613.00041
2	4	32962.57106
3	8	21379.64701
4	12	29499.05166
5	14	12065.95155
6	16	26973.81732
7	18	23929.58449




--
View this message in context: http://r-sig-geo.2731867.n2.nabble.com/for-loop-with-kde-ks-package-function-not-working-tp7582943.html
Sent from the R-sig-geo mailing list archive at Nabble.com.



More information about the R-sig-Geo mailing list