2015-02-07 33 views
2

一個非常簡單的爲那些其中R使用LM

full <- lm(hello~., hellow) 

的深入瞭解在上述說明書中指定與所選術語模型,正在使用線性迴歸和在數據集hellow你好被建模針對所有變量。

我在hellow 33個變量;我希望將其中的一些作爲自變量。這些變量的名稱帶有含義,所以我真的不想將它們重命名爲x1x2等。

如何在不必鍵入變量的個別名稱(因爲這非常繁瑣)的情況下指定從整羣中選擇一些變量?

我試圖

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)]'

+1

密切相關:http://stackoverflow.com/questions/22253688/add-formula-terms-programmatically/22254121#22254121 – 2015-02-07 17:30:49

回答

3

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 
+0

謝謝,我得到這個錯誤: eval(expr,envir,enclos)中的錯誤: 找不到對象'hello' – oivemaria 2015-02-07 22:48:40

+0

數據集hellow中是否有'hello'變量???可能無法解決這個問題,但沒有可重現的例子。 .. – 2015-02-08 00:16:23

+0

是的,絕對 - 作爲一個變量,我在hellow中打個招呼。你是指可重現的例子嗎?是不是代碼被認爲是可重現的例子? – oivemaria 2015-02-08 01:05:12