如何在R中的lm()函数中使用变量?

问题描述 投票:1回答:3

让我们说我有一个数据框(df),其中包含两列,分别为“ height”和“ weight”。

假设我定义:

x = "height"

如何在lm()函数中使用x? df[x]或仅使用x都不起作用。

r lm
3个回答
1
投票

两种方法:

使用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)

0
投票

我们可以使用glue创建公式


0
投票

运行x = "height"时,正在为变量x分配字符串。

© www.soinside.com 2019 - 2024. All rights reserved.