在R中使用apply函数时,如何在函数中使用原始参数名?

时间:2016-04-30 23:49:36

标签: 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函数时,我正在寻找在任何情况下使用原始名称的一般方法(不仅仅是线性回归)。

1 个答案:

答案 0 :(得分: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