简体   繁体   English

迭代 R 中的公式元素

[英]Iterate over formula elements in R

Is there a way how to iterate over formula in R?有没有办法在 R 中迭代公式? what I need to do lets say we have a formula given as: as.formula(hp ~ factor(gear) + qsec + am)我需要做的假设我们有一个公式: as.formula(hp ~ factor(gear) + qsec + am)

What I need to do is to iterate over elements of formula So I can create 3 model (3 because we use 3 regressors - no counting dummies)我需要做的是迭代公式的元素所以我可以创建 3 个 model (3 个因为我们使用 3 个回归量 - 没有计数假人)

I need to create first model as as.formula(hp ~ factor(gear)) , then second like as.formula(hp ~ factor(gear) + qsec) and lastly as.formula(hp ~ factor(gear) + qsec + am)我需要先创建 model as.formula(hp ~ factor(gear)) ,然后创建第二个as.formula(hp ~ factor(gear) + qsec) ,最后as.formula(hp ~ factor(gear) + qsec + am)

Can we somehow use just one regressor in one iterration, then use two and when use three?我们能否以某种方式在一次迭代中只使用一个回归量,然后使用两个,何时使用三个?

I need to automatize this for function and "hand" approach is not good我需要为 function 自动化这个,“手”的方法不好

My approach here: create a string using sprintf and paste (with collapse option), coerce it to a formula, and then loop over the elements you want to include.我的方法是:使用sprintf创建一个字符串并paste (带有collapse选项),将其强制转换为公式,然后循环遍历要包含的元素。

elements <- c("factor(gear)", "qsec", "am")

for (i in 1:length(elements)) {
    fmla <- as.formula(sprintf("hp ~ %s", paste(elements[1:i], collapse = " + ")))
    print(fmla)
    print(summary(lm(fmla, data = mtcars)))
}

If you need to parse the formula gave, you could do something like this before running the loop above (might need to be modified for your specific setup):如果您需要解析给出的公式,您可以在运行上面的循环之前执行以下操作(可能需要针对您的特定设置进行修改):

library(stringr)
input_fmla <- "as.formula(hp ~ factor(gear) + qsec + am)"
temp <- str_remove_all(input_fmla, "(as.formula\\([^ ]* ~ |\\)$)")
elements <- trimws(str_split(temp, pattern = "\\+")[[1]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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