Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substituting variable for string argument in function call

I am trying to call a function that expects a string as one of the arguments. However, attempting to substitute a variable containing the string throws an error.

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
like image 962
Hank Lin Avatar asked Jan 27 '23 03:01

Hank Lin


1 Answers

{jtools} uses non-standard evaluation so you can specify unquoted column names, e.g.

library(jtools)

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

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

...but it's not robustly implemented, so the (common!) case you've run into breaks it. If you really need it to work, you can use bquote to restructure the call (with .(...) around what you want substituted), and then run it with eval:

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

...but this is diving pretty deep into R. A better approach is to make the plot yourself using an ordinary plotting library like {ggplot2}.

like image 59
alistaire Avatar answered Mar 06 '23 03:03

alistaire