在函数调用中用变量替换字符串参数

问题描述 投票:4回答:2

我试图调用一个函数,该函数需要一个字符串作为参数之一。但是,尝试替换包含该字符串的变量会引发错误。

library(jtools)

# Fit linear model
fitiris <- lm(Petal.Length ~ Petal.Width * Species, data = iris)

# Plot interaction effect: works!
interact_plot(fitiris, pred = "Petal.Width", modx = "Species")

# Substitute variable name for string: doesn't work!
predictor <- "Petal.Width"
interact_plot(fitiris, pred = predictor, modx = "Species")

Error in names(modxvals2) <- modx.labels : 
  attempt to set an attribute on NULL
r linear-regression interaction
2个回答
5
投票

{jtools}使用非标准评估,因此您可以指定未加引号的列名称,例如

library(jtools)

fitiris <- lm(Petal.Length ~ Petal.Width * Species, data = iris)

interact_plot(fitiris, pred = Petal.Width, modx = Species)

...但它没有得到很好的实施,所以你遇到的(普通!)案例会破坏它。如果你确实需要它可以工作,你可以使用bquote来重组调用(用你想要替换的.(...)),然后使用eval运行它:

predictor <- "Petal.Width"
eval(bquote(interact_plot(fitiris, pred = .(predictor), modx = "Species")))

...但这是潜水深入R.更好的方法是使用像{ggplot2}这样的普通绘图库自己创建绘图。


2
投票

我是这个包的开发者。

简短说明:此函数刚刚被移动到一个名为interactions的新包中,该包正在被添加到CRAN中。如果你想在它到达CRAN之前安装它(我希望这在一周内发生),你需要使用这段代码从Github下载它:

if (!requireNamespace("remotes") {
  install.packages("remotes")
}
remotes::install_github("jacob-long/interactions")

在这个新版本中,我改变了非标准评估,以遵循tidyeval模型。这意味着编写一个插入predmodx和/或mod2参数的函数应该更直接。

例如:

library(interactions)

plot_wrapper <- function(my_model, my_pred, my_modx) {
  interact_plot(my_model, pred = !! my_pred, modx = !! my_modx)
}

fiti <- lm(Income ~ Frost + Murder * Illiteracy, data = as.data.frame(state.x77))
plot_wrapper(fiti, my_pred = "Murder", my_modx = "Illiteracy") # Works
pred_var <- "Murder"
modx_var <- "Illiteracy"
plot_wrapper(fiti, my_pred = pred_var, my_modx = modx_var) # Works

或者只是举一个在循环中使用变量的例子......

variables <- c("Murder", "Illiteracy")
for (var in variables) {
  print(interact_plot(fiti, pred = !! var, modx = !! (variables[variables != var])))
}
© www.soinside.com 2019 - 2024. All rights reserved.