Rename the variable name list () not the index in R

I am performing regressions on a list () of elements using a for loop and I would like to replace the reference to the input of the given list with the name of that variable, not its index. For example:

frame <- data.frame(y = rnorm(10), x1 = rnorm(10), x2 = rnorm(10), x3 = rnorm(10) ) 
x.list <- list(frame$x1,frame$x2,frame$x3)  
fit <- list()

for(i in 1:length(x.list)){ fit[[i]] <- summary(lm(frame$y ~ x.list[[i]]))}         
fit

      

I would like each item to match "x1", "x2", "x3" instead of "x.list [[i]]". Thanks for any thoughts on this.

+3


source to share


2 answers


Don't define x.list

, just iterate over the names:

fit <- vector("list",3)
for ( i in c("x1","x2","x3") ) fit[[i]] <- summary(lm(frame$y ~ frame[[i]]))

      


Save lm

instead.
You probably need more than a summary, so just keep lm

s:



xs     <- c("x1","x2","x3")
xs     <- setNames(xs,xs)
fit_lm <- lapply(xs,function(i)lm(frame$y ~ frame[[i]]))

      

You can view summary

with lapply(fit_lm,summary)

, and also see the odds with

sapply(fit_lm,`[[`,"coefficients")
#                    x1         x2          x3
# (Intercept) 0.1417501  0.2974165  0.25085281
# frame[[i]]  0.2318912 -0.1468433 -0.08783857

      

+3


source


If you want to return a value, lapply

is preferred:

xs <- names(frame)[-1]

setNames(
  lapply(xs, function(x, dat) {
    f <- as.formula(paste("y", x, sep = "~"))
    summary(lm(f, data = dat))
  }, dat = frame), 
  xs)

      



However, the same strategy will work with a loop for

.

+1


source







All Articles