2014-09-01 79 views
0

我有一個貝殼長度和高度的數據集,但在某些年份沒有記錄高度。我正在嘗試使用記錄身高和身高的數據年數的線性迴歸,以便用NAs生成年份的高度。 最重要的是,我希望它爲我的每個評估領域做這個迴歸。迴歸Lm並替換NA

到目前爲止,這是我的;

for(a in unique(all_data$Assessment_area)) { 
r1 <- lm(Height_t2~Length_t2,data=all_data[!is.na(all_data$Height_t2)&all_data$Assessment_area==a,]) #Regression model for all shells with L&H 
print(a) 
print(r1) 
} 

這給了我,我需要爲每個評估區域(我然後插入下面即與0.8871 0.5143代碼,但此刻一個個)的輸出。 我的代碼的下一位是創建一個新的列,如下所示,每次輸入生成的值。有沒有辦法將這些線路合併到前一個循環中?

all_data$Height_r1 <- all_data$Length_t2*0.8871+0.5143 #Apply regression relationship to new column 
all_data$Height_r1[!is.na(all_data$Height_t2)] <-all_data$Height_t2[!is.na(all_data$Height_t2)] #Add original heights 

任何幫助表示讚賞

+0

什麼是08871和0.5143?這是上一步中LM的結果嗎? – bsg 2014-09-01 09:51:42

+0

是的,但有5個評估區域,所以有5組結果,所以我還需要指定只使用該區域的計算迴歸來替換每個評估區域的高度值。以前,當我使用這個代碼時,我剛剛對所有的炮彈都使用了一個單一的迴歸方程,但我認爲區域/評估區域規模迴歸會更準確。 – 2014-09-01 10:03:37

回答

1

您可以訪問使用$操作上的彙總函數的線性迴歸的結果。在這種情況下,你會做

r1coefs <- summary(r1)$coefficients 
intercept <- r1coeffs[1] 
slope <- r1coeffs[2] 

然後可以將這些變成你的循環如下:

for(a in unique(all_data$Assessment_area)) 

{ r1 <- lm(Height_t2~Length_t2,data=all_data[!is.na(all_data$Height_t2)&all_data$Assessment_area==a,]) #Regression model for all shells with L&H 
print(a) 
print(r1) 
#access the linear regression coefficients and store them   
r1coefs <- summary(r1)$coefficients 
intercept <- r1coeffs[1] 
slope <- r1coeffs[2] 

#use the stored regression coefficients on the new data 
all_data$Height_r1 <- all_data$Length_t2*slope+intercept #Apply regression relationship to new column 
all_data$Height_r1[!is.na(all_data$Height_t2)] <-all_data$Height_t2[!is.na(all_data$Height_t2)] #Add original heights 
} 
+0

謝謝bsg,代碼運行良好,但是當我檢查輸出時,其中一些已經關閉了。我只能在計算器上生成5個評估區域高度中的一個。例如,許多人都不太合適。對於評估區域A,打印出的坡度爲0.8877,截距爲0.8175,因此長度爲44 * 0.8877 + 0.8175,我得到39.8763,但是r產生39.3548,這對於某些高度來說是足夠的差異以便湊到錯誤的mm。我想不出爲什麼會出現這種情況? – 2014-09-01 10:44:13

+0

嗯看起來它只是對它們使用一個等式,這就是爲什麼一個評估區域應該是這樣,其他區域不是這樣。循環中必須有一些缺失。 – 2014-09-01 10:54:10

0

問題解決了:)只是需要一些額外的比特使用存儲的迴歸時指定Assessment_area數據 ;

for(a in unique(all_data$Assessment_area)) { 
r1 <- lm(Height_t2~Length_t2,data=all_data[!is.na(all_data$Height_t2) &all_data$Assessment_area==a,]) 
#Regression model for all shells with L&H 
print(a) 
print(r1) 
#access the linear regression coefficients and store them   
r1coeffs <- summary(r1)$coefficients 
    intercept <- r1coeffs[1] 
slope <- r1coeffs[2] 

    #use the stored regression coefficients on the new data 

    all_data[all_data$Assessment_area==a,"Height_r1"] <- all_data [all_data$Assessment_area==a,"Length_t2"]*slope+intercept #Apply regression relationship to new column 

} 

#Add original heights   
all_data$Height_r1[!is.na(all_data$Height_t2)] <-all_data$Height_t2[!is.na(all_data$Height_t2)]