I have a reserved list. Each of these reserved lists correspond to an independent variable. Is there a short cut for the bolded part below.
To be clear, I need to find a way to write a short cut for: lm(y~res_list[[1]] res_list[[2]] res_list[[3]] .... res_list[[10]]
CodePudding user response:
If you want to use all of the elements of res_list
(other than y
, if res_list
has an element named y
), then @RitchieSacramento's suggestion
lm(y ~ ., data = res_list)
should work. The semantics of .
are documented in ?formula
.
Otherwise, you can always build your formula programmatically:
f <- function(formula, index) {
n <- length(formula)
rhs <- formula[[n]]
l <- lapply(index, function(i) bquote(.(rhs)[[.(i)]]))
plus <- function(x, y) call(" ", x, y)
formula[[n]] <- Reduce(plus, l)
formula
}
f(y ~ res_list, 1:10)
y ~ res_list[[1L]] res_list[[2L]] res_list[[3L]] res_list[[4L]]
res_list[[5L]] res_list[[6L]] res_list[[7L]] res_list[[8L]]
res_list[[9L]] res_list[[10L]]
f(hello ~ world, c(1L, 2L, 3L, 5L, 8L))
hello ~ world[[1L]] world[[2L]] world[[3L]] world[[5L]]
world[[8L]]