让我们说我有一个数据框(df),其中包含两列,分别为“ height”和“ weight”。
假设我定义:
x = "height"
如何在lm()
函数中使用x? df[x]
或仅使用x都不起作用。
两种方法:
使用paste
创建公式
x = "height"
lm(paste0(x, '~', 'weight'), df)
或使用reformulate
lm(reformulate("weight", x), df)
与mtcars
数据集一起使用可重现的示例:
x = "Cyl"
lm(paste0(x, '~', 'mpg'), data = mtcars)
#Call:
#lm(formula = paste0(x, "~", "mpg"), data = mtcars)
#Coefficients:
#(Intercept) mpg
# 11.2607 -0.2525
并与]相同>
lm(reformulate("mpg", x), mtcars)
我们可以使用glue
创建公式
运行x = "height"
时,正在为变量x
分配字符串。