简体   繁体   中英

How can I use the original argument name in a function when using an apply function in R?

Whenever I use an apply function, using a dummy variable in the anonymous function results in the name of that dummy variable being used internally. How can I use the original variable name internally to avoid complications when processing the resulting list?

Below is an example describing what I mean:

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  

I would like each linear regression above to use the names Col1 , Col2 , etc. instead of x in every single regression. Furthermore, I am looking for a general way to use the original names in any situation (not just linear regression) when I use an apply function.

One approach is to do it in two steps as follows:

1) First run the regressions as you are doing 2) Replace the coefficient name and also the formula

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)
}

Resulting output is as follows:

$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  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM