2016-04-30 92 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,但是不管我在做什么,都会自动执行。我的问题是关于如何做到这一点。不只是如何在线性回归中做到这一点。 –

相关问题