【发布时间】:2023-02-24 11:46:33
【问题描述】:
假设我想写anscombe %>% lm_tidy("x1", "y1")(实际上,我想写anscombe %>% lm_tidy(x1, y1),其中x1和y1是数据框的一部分).因此,由于以下功能似乎有效:
plot_gg <- function(df, x, y) {
x <- enquo(x)
y <- enquo(y)
ggplot(df, aes(x = !!x, y = !!y)) + geom_point() +
geom_smooth(formula = y ~ x, method="lm", se = FALSE)
}
我开始编写以下函数:
lm_tidy_1 <- function(df, x, y) {
x <- enquo(x)
y <- enquo(y)
fm <- y ~ x ##### I tried many stuff here!
lm(fm, data=df)
}
## Error in model.frame.default(formula = fm, data = df, drop.unused.levels = TRUE) :
## object is not a matrix
passing in column name as argument 中的一条评论指出,embrace {{...}} 是引号-反引号模式的简写符号。不幸的是,两种情况下的错误消息都不同:
lm_tidy_2 <- function(df, x, y) {
fm <- !!enquo(y) ~ !!enquo(x) # alternative: {{y}} ~ {{x}} with different errors!!
lm(fm, data=df)
}
## Error:
## ! Quosures can only be unquoted within a quasiquotation context.
这似乎有效(基于@jubas's answer,但我们坚持使用字符串处理和paste):
lm_tidy_str <- function(df, x, y) {
fm <- formula(paste({{y}}, "~", {{x}}))
lm(fm, data=df)
}
再一次,{{y}} != !!enquo(y)。但更糟糕的是:以下函数出现与之前相同的 Quosure 错误:
lm_tidy_str_1 <- function(df, x, y) {
x <- enquo(x)
y <- enquo(y)
fm <- formula(paste(!!y, "~", !!x))
lm(fm, data=df)
}
- 是
{{y}} != !!enquo(y)吗? - 如何将数据变量传递给
lm?编辑:对不起,我的许多试验都有遗留问题。我想直接将数据变量(比如
x1和y1)传递给将它们用作公式组件的函数(例如lm)而不是它们的字符串版本("x1"和@987654342 @): 我尽量避免使用字符串,从用户的角度来看,它更加精简。
【问题讨论】:
-
首先,您是传递带引号的变量还是不带引号的变量?即字符串与符号?另外,如果您要编写这样的函数,为什么不直接使用
lm.fit? -
举例说明您希望如何使用它,以及为什么需要它
-
你知道包
rlang- 它有元编程的功能。 - 首先 - 请向我们展示您想要抽象的代码 - 哪些代码 - 以及您想要抽象的代码的哪些部分? -
您可以使用
x <- if (is.character(substitute(x))) x else deparse(substitute(x))将带引号或不带引号的变量转换为字符串。然后lm(reformulate(x, y), data = data)一行代码不需要添加依赖 -
@rawr ino 需要
if else。只需as.charcter(substitute(x))即可。还要检查提供的答案
标签: r function lazy-evaluation lm