[英]specify model with selected terms using lm
對於那些熟悉R的人來說非常簡單
full <- lm(hello~., hellow)
在以上規范中,使用了線性回歸,並針對數據集hellow
中的所有變量對hello進行了建模。
我在33個變數hellow
; 我希望將其中一些指定為自變量。 這些變量的名稱帶有含義,所以我真的不想將它們重命名為x1
x2
等。
我不必鍵入變量的單個名稱(因為這很繁瑣),如何在整個變量集中指定一定數量的變量?
我試過了
full <- lm(hello~hellow[,c(2,5:9)]., hellow)
但這給了我一個錯誤"Error in model.frame.default(formula = hello ~ hellow[, : invalid type (list) for variable 'hellow[, c(2, 5:9)]'
reformulate
構造將根據給定的變量名稱構造一個公式,如下所示:
(首先構建數據):
set.seed(101)
hellow <- setNames(as.data.frame(matrix(rnorm(1000),ncol=10)),
c("hello",paste0("v",1:9)))
現在運行代碼:
ff <- reformulate(names(hellow)[c(2,5,9)],response="hello")
full <- lm(ff, data=hellow)
應該管用。 (在此示例中工作正常。)
我想到了一個更簡單的解決方案。 只需先選擇要使用的列/變量:
hellow_red <- hellow[,c(1,2,5,9)]
full2 <- lm(hello~., data=hellow_red)
all.equal(coef(full),coef(full2)) ## TRUE
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.