Is it possible to pass method names as a wrapper function argument in R?

Viewed 44

I am working on a R script based on RSelenium library that is aimed to use "scraping scenarios" in form of a tibble. Therefore I would like to use a function, that according to certain arguments would return the certain action of remote driver. The general idea is to have something that will convert arguments to methods syntax:

scraper(driver, method, arguments) == driver$method(arguments)

So if I call:

scraper(remDr, "open") - it simply does - remDr$open()
scraper(remDr, "navigate", "https://google.com") - it does - remDr$navigate("https://google.com")
scraper(remDr, "findElement", list(using = "xpath", "[@=...]") - it does - remDr$findElement("xpath", "[@=...]")

Here is the sample that I've ended up with:

scraper <- function(driver, method, arguments = "") {

  open <- function(driver) {
    return(
        driver$open()
    )
  }

  close <- function(driver) {
    return(
        driver$close()
      )
  }

  navigate <- function(driver, arguments) {
    return(
        driver$navigate(arguments)
      )
  }

  findElement <- function(driver, arguments) {
    return(
        driver$findElement(arguments)
      )
  }

  scraperMethods <- list(open = open, 
                         close = close, 
                         navigate = navigate, 
                         findElement = findElement)

  return(scraperMethods[[method]](arguments))

}

The double brackets convention in scraperMethods[[method]] seems to work in global environment but when i call

scraper(remDr, "open")

or other methods defined so far within the scraper function. It throws an error:

Error: $ operator is invalid for atomic vectors

So my questions are: 1. Is this the right approach? 2. If not - is there more convenient way to achieve my goal?

Thanks in advance for all answers.

0 Answers
Related