问题
I am running a simulation and need to test the performance of different sized formulas. Drawing from data frame with columns V1, V2, V3... Vk, I need to programmatically create formulas like fit <- ols(y ~ V1 + V2 + V3, data=dataframe)
and so forth.
How can I code the formula to be able to scale the length of the formula?
回答1:
You can convert text to a formula:
vars <- c(1, 2, 4)
formula.text <- paste0("y ~ V", paste(vars, collapse=" + V"))
formula.text
# [1] "y ~ V1 + V2 + V4"
library(rms)
fit <- ols(as.formula(formula.text), data=dataframe)
回答2:
You can use reformulate
:
k <- 4
reformulate(paste0("V", seq(k)), response = "y")
# y ~ V1 + V2 + V3 + V4
来源:https://stackoverflow.com/questions/22253688/add-formula-terms-programmatically