r - R 的 lm() 中的分数频率权重
问题描述
我理解lm
将weights
其视为“分析”权重,这意味着观察只是相互加权(例如,对 = 2lm
的观察的加权是weight
= 1 的两倍weight
),并且N
模型的整体不受影响。另一方面,“频率”权重将允许模型与N
数据中的实际观察数不同。
人们之前曾询问过 R 中的频率权重,但据我所知,之前的问题与调查数据有关。我没有使用调查数据来回答这个问题。
我想实现小于 1 的频率权重,这会导致模型N
小于数据中的实际行数。例如,如果nrow(df)
= 8 且所有观测值weight
= 0.5,则模型N
应为 4,标准误应反映这种差异。lm
据我所知,不能以这种方式使用基础 R 的权重:
library(tidyverse)
library(broom)
df.unweighted <- tribble(
~x, ~y, ~w,
0, 10, 1,
0, 20, 1,
1, 40, 1,
1, 50, 1,
) %>%
bind_rows(., .) # make twice as large
df.weighted <- df.unweighted %>%
mutate(w = 0.5)
lm(data=df.unweighted, y~x, weights=w) %>%
tidy
#> # A tibble: 2 x 5
#> term estimate std.error statistic p.value
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 (Intercept) 15. 2.89 5.20 0.00202
#> 2 x 30 4.08 7.35 0.000325
lm(data=df.weighted, y~x, weights=w) %>%
tidy
#> # A tibble: 2 x 5
#> term estimate std.error statistic p.value
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 (Intercept) 15. 2.89 5.20 0.00202
#> 2 x 30.0 4.08 7.35 0.000325
# identical
我正在寻找的可以通过stata
使用来实现iweights
。注意模型N
和标准误差:
library(RStata)
stata("reg y x [iweight=w]",
data.in = df.weighted)
#> . reg y x [iweight=w]
#>
#> Source | SS df MS Number of obs = 4
#> -------------+------------------------------ F( 1, 2) = 18.00
#> Model | 900 1 900 Prob > F = 0.0513
#> Residual | 100 2 50 R-squared = 0.9000
#> -------------+------------------------------ Adj R-squared = 0.8500
#> Total | 1000 3 333.333333 Root MSE = 7.0711
#>
#> ------------------------------------------------------------------------------
#> y | Coef. Std. Err. t P>|t| [95% Conf. Interval]
#> -------------+----------------------------------------------------------------
#> x | 30 7.071068 4.24 0.051 -.4243492 60.42435
#> _cons | 15 5 3.00 0.095 -6.513264 36.51326
#> ------------------------------------------------------------------------------
在我的实际使用中,并非所有观察结果都具有相同的权重。我只是在这里这样做是为了便于演示。