R/invDistWeight.R

Defines functions invDistWeight

invDistWeight <- function(longY, # Longitude of "ependent" locations (locations we want to estimate for)
                          latY, # Latitude of "dependent" locations (locations we want to estimate for)
                          longX, # Longitude of "explanatory" locations
                          latX, # Latitude of "explanatory" locations,
                          X, # Variable of interest
                          P = 1, # Adjust weights
                          OUTL = quantile(abs(X), .99), # Skip extreme obs, NULL = no skiping
                          cores = NULL # NULL = All, integer = number of cores
) {

  if(!is.null(OUTL)){
    ind0 <- abs(X) < OUTL
    longX <- longX[ind0]
    latX <- latX[ind0]
    X <- X[ind0]
  }

  library(parallel)

  if(is.null(cores)){
    nc <- detectCores()
  }else{
    nc <- cores
  }
  if(nc > 1){
    cl <- makeCluster(nc)

    clusterExport(cl, c("longY", "latY", "longX", "latX", "X", "P"), envir = environment())
    clusterEvalQ(cl, library(k1))

    l_idw <- parLapply(cl, splitvec(1:length(longY), nc), function(i){
      idw1( long0 = longY[i], long1 = longX,
            lat0 = latY[i], lat1 = latX,
            x = X, P = P)})

    stopCluster(cl)
  }

  do.call(c, l_idw)
}
steinarv/k1 documentation built on Oct. 19, 2017, 4:41 a.m.