![](/img/trans.png)
[英]How to pass weights in lm object as a variable from outside the function and refer the column name as weight in the model form?
[英]How to pass "weights" column name as a variable in R's lm?
下面的代碼創建一個帶有 R 的 lm 的線性模型,然后是一個帶有權重列的加權模型。 最后,我嘗試使用變量weight_col
傳入權重列名稱,但失敗了。 我很確定它在 df 中尋找“weight_col”,然后調用者的環境找到一個長度為 1 的變量,並且長度不匹配。
我如何讓它使用 weight_col 作為 df 中權重列的名稱?
我已經嘗試了幾種組合,但都沒有成功。
> df <- data.frame(
x=c(1,2,3),
y=c(4,5,7),
w=c(1,3,5)
)
> lm(y ~ x, data=df)
Call:
lm(formula = y ~ x, data = df)
Coefficients:
(Intercept) x
2.333 1.500
> lm(y ~ x, data=df, weights=w)
Call:
lm(formula = y ~ x, data = df, weights = w)
Coefficients:
(Intercept) x
1.947 1.658
> weight_col <- 'w'
> lm(y ~ x, data=df, weights=weight_col)
Error in model.frame.default(formula = y ~ x, data = df, weights = weight_col, :
variable lengths differ (found for '(weights)')
> R.version.string
[1] "R version 3.6.3 (2020-02-29)"
您可以將數據框名稱與提取器運算符一起使用:
lm(y ~ x, data = df, weights = df[[weight_col]])
或者您可以使用函數get
:
lm(y ~ x, data = df, weights = get(weight_col))
我們可以使用[[
來提取列的值
lm(y ~ x, data=df, weights=df[[weight_col]])
或者用tidyverse
library(dplyr)
df %>%
summarise(model = list(y ~ x, weights = .data[[weight_col]]))
您的第一個示例 if weights = w
,它使用非標准評估在df
的上下文中查找w
。 到目前為止,這對於交互式使用來說是正常的。
你的第二組是weights = weight_col
解析為weights = "w"
,這是非常不同的。 R 的非標准(或標准)評估中沒有任何內容是有意義的。
正如我在評論中所說,使用帶有[[
的標准評估形式。
lm(y ~ x, data=df, weights=df[[weight_col]])
# Call:
# lm(formula = y ~ x, data = df, weights = df[[weight_col]])
# Coefficients:
# (Intercept) x
# 1.947 1.658
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.