更新时间:2022-03-28 22:37:21
如何将公式作为字符串使用?许多基本的R模型,例如lm()
都接受字符串公式(否则,您始终可以使用formula()
).在这种情况下,您可以使用gsub()
:
How about working with the formula as a string? Many base R models like lm()
accept a string formulas (and you can always use formula()
otherwise). In this case, you can use something like gsub()
:
f1 <- "y ~ x + z"
f2 <- "y ~ b*x + z"
gsub("x", "(x_part1 + x_part2)", f1)
#> [1] "y ~ (x_part1 + x_part2) + z"
gsub("x", "(x_part1 + x_part2)", f2)
#> [1] "y ~ b*(x_part1 + x_part2) + z"
例如,使用mtcars
数据集,并说我们要用disp + hp
(x_part1 + x_part2)替换mpg
(x):
For example, with mtcars
data set, and say we want to replace mpg
(x) with disp + hp
(x_part1 + x_part2):
f1 <- "qsec ~ mpg + cyl"
f2 <- "qsec ~ wt*mpg + cyl"
f1 <- gsub("mpg", "(disp + hp)", f1)
f2 <- gsub("mpg", "(disp + hp)", f2)
lm(f1, data = mtcars)
#>
#> Call:
#> lm(formula = f1, data = mtcars)
#>
#> Coefficients:
#> (Intercept) disp hp cyl
#> 22.04376 0.01017 -0.02074 -0.56571
lm(f2, data = mtcars)
#>
#> Call:
#> lm(formula = f2, data = mtcars)
#>
#> Coefficients:
#> (Intercept) wt disp hp cyl
#> 20.421318 1.554904 0.026837 -0.056141 -0.876182
#> wt:disp wt:hp
#> -0.006895 0.011126