Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding eval-parse or do.call

Tags:

r

ggplot2

I am trying to select a theme from ggplot2 based on some string given. For demo purposes, consider the following code:

library(dplyr); library(ggplot2)
mtcars %>% 
  ggplot(aes(mpg, wt))+
  geom_point() -> p
all_ggplot2_funs <- getNamespaceExports("ggplot2")
p +
eval(parse(text=paste0(all_ggplot2_funs[grep("theme_", all_ggplot2_funs)][15],
                       "()")))

This works fine and would allow me to use theme_minimal. However, from a security point of view as highlighted in past threads on the eval-parse scenario in different languages, I would like to avoid this.

I could probably use do.call but was looking at something akin to python's () where I can just call a function based on a string e.g.

methods = {pi: math.pi, sum: math.sum}
methods["pi"]()

What could be an R base way to achieve this?

like image 720
NelsonGon Avatar asked Apr 10 '26 00:04

NelsonGon


1 Answers

We may use getFunction

library(ggplot2)
p1 <- p + 
   getFunction(all_ggplot2_funs[grep("theme_", all_ggplot2_funs)][15])()

-checking

> p2 <- p + theme_minimal()
> all.equal(p1, p2)
[1] TRUE
like image 83
akrun Avatar answered Apr 12 '26 15:04

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!