[R] how to store estimates results as scalars of a matrix?

Uwe Ligges ligges at statistik.uni-dortmund.de
Sat Jun 19 13:38:02 CEST 2004


Joao Pedro W. de Azevedo wrote:
> Dear R users,
> 
> I've written a loop to generate Moran's test (spdep package) on serval
> subsamples of a large dataset. See below a short example.
> 
> My loop is working fine, however I would like to be able to store the test
> results as lines of a matrix, that I would latter be able to export as a
> dataset. My problem is that I'm not sure how I could do this using R.
> 
> Any help will be much appreciated.
> 
> All the very best,
> 
> JP
> 
> 
> 
> coords2 <- as.matrix(jcdist.data[1:87, 6:7])
> 
> col.tri.nb<-tri2nb(coords2)
> 
> for(n in c(1,88,175,262,349)) {
>     f<- n+86
>     work <- jcdist.data[n:f, 10:12]
> 
>     res <-moran.test(spNamedVec("res1", work), nb2listw(col.tri.nb,
> style="W"))
>     moran<-res$estimate[1]
>     upper<-res$estimate[1] + (qnorm(0.025, lower.tail=FALSE)
> *sqrt(res$estimate[3]))
>     lower<-res$estimate[1] - (qnorm(0.025, lower.tail=FALSE)
> *sqrt(res$estimate[3]))
>     
>     print(moran)
>     print(upper)
>     print(lower)

[...]

 > }


What you really want is something along the lines (untested!):

  coords2 <- as.matrix(jcdist.data[1:87, 6:7])
  col.tri.nb <- tri2nb(coords2)
  N <- c(1, 88, 175, 262, 349)
  # generate the transposed matrix of results, because
  # it is faster to assign into columns rathger than into rows:
  results <- mattrix(nrow = 3, ncol = length(N))
  # the following calculations shouldn't be done within the loop -
  # efficiency!
  f <- N + 86
  qn <- qnorm(0.025, lower.tail = FALSE)
  for(i in seq(along = N)) {
      work <- jcdist.data[n[i]:f[i], 10:12]
      res <- moran.test(spNamedVec("res1", work),
                        nb2listw(col.tri.nb, style = "W"))
      # calculate the following just once:
      ci <- qn * sqrt(res$estimate[3])
      results[,i] <- res$estimate[1] + c(1, ci, -ci)
  }
  t(results)
  colnames(results) <- c("Moran", "upper", "lower")


Uwe Ligges




More information about the R-help mailing list