Runbin Sun
Runbin Sun

Reputation: 45

r - How to Create loop for plotting in dabestr?

I am using dabestr for plotting estimation plots, for a single variable I succeed, but I want to create a batch of plots with the for loop and it not work.

library(dabestr)
plot(dabest(iris, Species,  Petal.Width, idx = c("setosa", "versicolor"), paired = FALSE))

I want to plot Sepal.Length, Sepal.Width, Petal.Length, Petal.Width in a for loop. Would anyone help? Thank you!

Upvotes: 2

Views: 262

Answers (1)

RoB
RoB

Reputation: 1994

The issue is not with the for statement, it's with the dabest function. It's made to only accept column names as given in .data so a string with the column name doesn't work...

After digging a bit, I found this answer very helpful for dplyr related problems with variable names.

library(dabestr)
library(ggpubr) # for ggarrange

to_plot <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")
plots <- lapply(to_plot, function(co){
  plot(dabest(iris, Species, UQ(rlang::sym(co)), idx = c("setosa", "versicolor"), paired = FALSE))
})

ggarrange(plotlist = plots, nrow = 2, ncol = 2)

Note that UQ(rlang::sym(my_string)) is doing the magic here. This yields the following plot.

enter image description here

Upvotes: 2

Related Questions