I haven't used spdep::lagsarlm
but it is very easy to replicate the way lm
uses weights using the following method:
Let's assume you have a data.frame df
defined as:
df <- data.frame(a=runif(10), b=runif(10))
> df
a b
1 0.8266429 0.43591733
2 0.4624063 0.93180891
3 0.7085656 0.36468984
4 0.3339251 0.79093356
5 0.8236406 0.39687242
6 0.8266429 0.83213817
7 0.4624063 0.34714824
8 0.7085656 0.01812133
9 0.3339251 0.54498829
10 0.8236406 0.73677156
and a weights vector defined as:
c(1,1,1,1,2,2,2,2,2,2)
Running an lm
on the above data produces the following results:
> lm(a~b, data=df, weights=c(1,1,1,1,2,2,2,2,2,2))
Call:
lm(formula = a ~ b, data = df, weights = c(1, 1, 1, 1, 2, 2,
2, 2, 2, 2))
Coefficients:
(Intercept) b
0.6672 -0.0467
Let's see now how the function lm
actually uses the weights vector.
We start by replicating the rows of the data.frame df by the number defined in the weights like this:
replicate_rows <- rep(1:nrow(df), c(1,1,1,1,2,2,2,2,2,2))
Rows with a weight of 2 appear twice as you can see below:
> replicate_rows
[1] 1 2 3 4 5 5 6 6 7 7 8 8 9 9 10 10
Use the above to make a new data.frame df2
that uses those rows:
df2 <- df[replicate_rows, ]
> df2
a b
1 0.8266429 0.43591733
2 0.4624063 0.93180891
3 0.7085656 0.36468984
4 0.3339251 0.79093356
5 0.8236406 0.39687242
5.1 0.8236406 0.39687242
6 0.8266429 0.83213817
6.1 0.8266429 0.83213817
7 0.4624063 0.34714824
7.1 0.4624063 0.34714824
8 0.7085656 0.01812133
8.1 0.7085656 0.01812133
9 0.3339251 0.54498829
9.1 0.3339251 0.54498829
10 0.8236406 0.73677156
10.1 0.8236406 0.73677156
I have replicated the rows of the dataframe df according to the weights. Let's run an lm
now without the use of weights:
> lm(a~b, data=df2)
Call:
lm(formula = a ~ b, data = df2)
Coefficients:
(Intercept) b
0.6672 -0.0467
As you can see the results are exactly the same!
You can use the above to weigh your data.frame accordingly and then use it in your spdep::lagsarlm
function.