簡體   English   中英

將變量名稱作為字符串傳遞給 lm 中的 contrasts() 參數

[英]Passing variable names as strings into the contrasts() argument in lm

我正在嘗試創建一個 function,它允許我將結果和預測變量名稱作為字符串傳遞給lm()回歸 function。 實際上我之前在這里問過這個問題,但是我在這里學到了一項新技術,並想嘗試在這種新格式中應用相同的想法。

這是過程

library(tidyverse)

# toy data
df <- tibble(f1 = factor(rep(letters[1:3],5)),
             c1 = rnorm(15),
             out1 = rnorm(15))

# pass the relevant inputs into new objects like in a function 
d <- df
outcome <- "out1"
predictors <- c("f1", "c1")

# now create the model formula to be entered into the model
form <- as.formula(
    paste(outcome,
          paste(predictors, collapse = " + "),
          sep = " ~ "))


# now pass the formula into the model
model <- eval(bquote( lm(.(form), 
                         data = d) ))

model

# Call:
#   lm(formula = out1 ~ f1 + c1, data = d)
# 
# Coefficients:
#   (Intercept)          f1b          f1c           c1  
#       0.16304     -0.01790     -0.32620     -0.07239 

所以這一切都很好,一種將變量傳遞給lm()的適應性方式。 但是如果我們想對階乘變量應用特殊的對比編碼呢? 我試過了

model <- eval(bquote( lm(.(form), 
                         data = d,
                         contrasts = list(predictors[1] = contr.treatment(3)) %>% setNames(predictors[1])) ))

但是得到了這個錯誤

Error: unexpected '=' in:
"                                                 data = d,
                                                 contrasts = list(predictors[1] ="

非常感謝任何幫助。

將其減少為生成錯誤的命令:

list(predictors[1] = contr.treatment(3))

結果是:

Error: unexpected '=' in "list(predictors[1] ="

當左側命名是需要評估的變量時, list() 似乎會窒息。

您使用 setNames() 的方法有效,但需要圍繞列表構建步驟本身進行包裝。

setNames(list(contr.treatment(3)), predictors[1])

Output 是一個包含對比矩陣的命名列表:

$f1
  2 3
1 0 0
2 1 0
3 0 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM