FKG
FKG

Reputation: 285

Creation of a spatial lag term in R

I've been struggling to find a way to create a spatial lag term of my dependent variable, weighted by the distance between capital cities of countries in my data. Although weights can be based upon different things, distance between capital cities is what I'm interested in (of course, first I need to find a way to create a spatial effect variable and then lag it).

The dependent variable (DV) is an ordinal measure ranging from 0 to 2.

Sample from my data (if it can be of any help):

country  year       DV                **spatial lag?**
USA      2000       NA                     
USA      2001       2                      
USA      2002       2                      
USA      2003       2                      
UK       2000       1                      
UK       2001       1                      
UK       2002       2                      
UK       2003       NA                    

I know that Stata has a command called spmon that can easily generate a spatial effect variable in monadic data (individual units not dyads). Unfortunately, I don't have Stata – but I guess there are ways of doing this in R?

UPDATE

I have the coordinates now – dyadic distances in kilometer. See the sample below.

ida  numb   idb      kmdist
USA  20     CAN       731
USA  31     BHM       1623
USA  40     CUB       1813
USA  41     HAI       2286
USA  42     DOM       2358
USA  51     JAM       2315
USA  52     TRI       3494
USA  53     BAR       3330

Exatly how can I generate a spatial lag term from the dataset above (lets assume that my DV – Y – is in the dataset)

Upvotes: 0

Views: 1313

Answers (1)

Jiaxiang
Jiaxiang

Reputation: 883

  1. Build a weight matrix.
  2. Double check the diag is all zero.
  3. Normalize ...
  4. One feature $X_1$
  5. The variance of w %*% x is smaller than x.
library(data.table)
sp <- data.table(
  location = letters[1:3]
  ,lat = c(20,40,60)
  ,lon = c(50,70,90)
)
sp
#>    location lat lon
#> 1:        a  20  50
#> 2:        b  40  70
#> 3:        c  60  90

library(tidyverse)
w_raw <- 
  sp %>% 
  dist(.$lat,.$lon,method = "euclidean", upper=TRUE) %>% 
  as.matrix()
#> Warning in dist(., .$lat, .$lon, method = "euclidean", upper = TRUE): 强制
#> 改变过程中产生了NA
w_raw
#>          1        2        3
#> 1  0.00000 34.64102 69.28203
#> 2 34.64102  0.00000 34.64102
#> 3 69.28203 34.64102  0.00000

w <- w_raw * (1/rowSums(w_raw))
x <- c(5,10,5)
w %*% x
#>       [,1]
#> 1 6.666667
#> 2 5.000000
#> 3 6.666667

Created on 2018-12-18 by the reprex package (v0.2.1)

Upvotes: 2

Related Questions