假设我有一个包含两列名为“height”和“weight”的数据框(df)。
假设我定义:
x = "height"
我如何在lm()
函数中使用x?使用df[x]
或仅使用x都不起作用。
两种方法:
使用paste
函数创建公式
x = "height"
lm(paste0(x, '~', 'weight'), df)
或者使用reformulate
lm(reformulate("weight", x), df)
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"
lm(glue::glue('{x} ~ weight'), data = df)
mtcars
数据集。x <- 'cyl'
lm(glue::glue('{x} ~ mpg'), data = mtcars)
#Call:
#lm(formula = glue::glue("{x} ~ mpg"), data = mtcars)
#Coefficients:
#(Intercept) mpg
# 11.2607 -0.2525
x = "height"
时,你正在将一串字符赋值给变量x
。
df <- data.frame(
height = c(176, 188, 165),
weight = c(75, 80, 66)
)
height
和weight
进行回归分析,可以采取以下两种方法:lm(height ~ weight, data = df)
# Call:
# lm(formula = height ~ weight, data = df)
#
# Coefficients:
# (Intercept) weight
# 59.003 1.593
lm(df$height ~ df$weight)
# Call:
# lm(formula = df$height ~ df$weight)
#
# Coefficients:
# (Intercept) df$weight
# 59.003 1.593
x
而不是height
,你必须有一个名为x
的变量(在你的df
或环境中)。你可以通过创建一个新变量来实现:x <- df$height
y <- df$weight
lm(x ~ y)
# Call:
# lm(formula = x ~ y)
#
# Coefficients:
# (Intercept) y
# 59.003 1.593
或者通过更改现有变量的名称:
names(df) <- c("x", "y")
lm(x ~ y, data = df)
# Call:
# lm(formula = x ~ y, data = df)
#
# Coefficients:
# (Intercept) y
# 59.003 1.593
tidyverse
,那么str_glue
将已经可以从stringr
包中使用。我相信它实际上是一个关于glue::glue
的小包装器,但这可能会减少对特定项目的依赖。 - Raul Guarini Riva