2016-04-30 96 views
0

每當我使用apply函數時,在匿名函數中使用一個虛擬變量會導致在內部使用該虛擬變量的名稱。如何在內部使用原始變量名稱以避免處理結果列表時出現複雜情況?在R中使用apply函數時,如何在函數中使用原始參數名稱?

下面是描述我的意思的例子:

set.seed(314) 

df <- data.frame(response = rnorm(500), 
       Col1 = rnorm(500), 
       Col2 = rnorm(500), 
       Col3 = rnorm(500), 
       Col4 = rnorm(500)) 

> apply(df[, 2:5], 2, function(x) lm(response ~ x, data = df)) 
$Col1 

Call: 
lm(formula = response ~ x, data = df) 

Coefficients: 
(Intercept)   x 
    0.074452  0.007713 


$Col2 

Call: 
lm(formula = response ~ x, data = df) 

Coefficients: 
(Intercept)   x 
    0.06889  0.07663 


$Col3 

Call: 
lm(formula = response ~ x, data = df) 

Coefficients: 
(Intercept)   x 
    0.07401  0.03512 


$Col4 

Call: 
lm(formula = response ~ x, data = df) 

Coefficients: 
(Intercept)   x 
    0.073668 -0.001059 

我想上面每一個線性迴歸在每一個迴歸到使用的名稱Col1Col2等代替x。此外,當我使用apply函數時,我正在尋找一種在任何情況下使用原始名稱的通用方法(不僅僅是線性迴歸)。

回答

0

一種方法是做它在兩個步驟如下:

1)首先運行迴歸爲你正在做 2)更換系數名以及式

l <- lapply(df[, 2:5], function(x) lm(response ~ x, data = df)) 
for (i in 1:length(l)) { 
    names(l[[i]]$coefficients)[2] <- names(l)[i] 
    l[[i]]$call <- gsub('x', names(l)[i], l[[i]]$call) 
} 

結果輸出如下所示:

$Col1 

Call: 
c("lm", "response ~ Col1", "df") 

Coefficients: 
(Intercept)   Col1 
    -0.04266  -0.07508 


$Col2 

Call: 
c("lm", "response ~ Col2", "df") 

Coefficients: 
(Intercept)   Col2 
    -0.04329  0.02403 


$Col3 

Call: 
c("lm", "response ~ Col3", "df") 

Coefficients: 
(Intercept)   Col3 
    -0.04519  -0.03300 


$Col4 

Call: 
c("lm", "response ~ Col4", "df") 

Coefficients: 
(Intercept)   Col4 
    -0.04230  -0.04506 
+0

謝謝,但它在公式調用中仍然有x,而不是Col1,Col2等。 –

+0

編輯瞭解決方案的答案......您只需要g把'call'字段加入並修改它。 – Gopala

+0

謝謝,但有沒有辦法在每種情況下自動執行該操作?因爲我不想在每個地方都用手動替換x,但是不管我在做什麼,都會自動執行。我的問題是關於如何做到這一點。不只是如何在線性迴歸中做到這一點。 –

相關問題