Add formula terms programmatically

怎甘沉沦 提交于 2019-12-11 08:20:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!