[英]How to do statistics and save results in a loop in R
在建模中,對依賴於線性,二次方,三次方和四元(?)形式的獨立變量進行單變量回歸是有幫助的,以查看哪個捕獲了統計數據的基本形狀。 我是一個相當新的R程序員,需要一些幫助。
這是偽代碼:
for i in 1:ncol(data)
data[,ncol(data) + i] <- data[, i]^2 # create squared term
data[,ncol(data) + i] <- data[, i]^3 # create cubed term
...and similarly for cubed and fourth power terms
# now do four regressions starting with linear and including one higher order term each time and display for each i the form of regression that has the highest adj R2.
lm(y ~ data[,i], ... )
# retrieve R2 and save indexed for linear case in vector in row i
lm(y tilda data[,i], data[,ncol(data) + i, ...]
# retrieve R2 and save...
結果是在原始x
變量的數據中由i
用列名索引的數據幀,以及四個回歸中的每個回歸的結果(均使用截距項運行)。
通常,我們通過查看圖來執行此操作,但是在這里有800個變量是不可行的。
如果您真的想幫忙編寫代碼,以自動將所需數量的指數變量插入數據中。
而且,這甚至都不會處理聚集在幾個簇中或僅與一個值相關的扭曲變量,等等。
我想說的最好的方法是使用R, poly()
的多項式函數。 假設您有一個獨立的數字變量x
和一個數字響應變量y
。
models=list()
for (i in 1:4)
models[[i]]=lm(y~poly(x,i),raw=TRUE)
raw=TRUE
部分可確保模型使用原始多項式,而不使用正交多項式。
如果要獲得其中一個模型,只需鍵入models[[1]]
或models[[2]]
等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.