1

Strings may be parsed and evaluated as described in https://stackoverflow.com/a/1743796/1659890 as follows:

eval(parse(text=paste0("c(",paste(c("'a'","'b'","'c'"),
c("'z'","'y'","'x'"), sep = "=", collapse = ","),")")))

c('a' = 'z', 'b' = 'y', 'c' = 'x')

Such an expression is useful in Shiny apps and Switch statements, i.e.

switch(EXPR = "a",
       "a" = "z",
       "b" = "y",
       "c" = "x"
       )

shinyApp(
  ui = fluidPage(
    uiOutput("selectUI"),
    "The selected value is:",
    textOutput("selectedValue")
  ),
  server = function(input, output, session){
    output$selectUI <- renderUI(
      selectInput("selectVariable",
                  choices = c("a" = "z",
                              "b" = "y"),
                  label = "My Label")
    )

    output$selectedValue <- renderText(input$selectVariable)
  }
)

In the R language, how might such an expression be constructed entirely programmatically with the following input? Acknowledging that " must be replaced with '?

list1 <- c("a","b","c")
list2 <- c("z","y","x")

Or the more likely case of a data.frame with two columns that are as.character.

Community
  • 1
  • 1

1 Answers1

3

do.call will be helpful. Pass it a list where the first argument is EXPR and the other arguments are the named list of alternatives:

list1 <- c("a","b","c")
list2 <- list("z","y","x")

names(list2) <- list1

do.call("switch", c("a", list2))
tmpname12345
  • 2,891
  • 18
  • 20
  • Thanks for this, it solves both the problem of using `switch` and `selectInput` for my shinyApp. `do.call` is quite foreign to my previous experience with the Wolfram Language, is this sort of thing peculiar to R? – Charlie Joey Hadley Jan 11 '16 at 22:30
  • I think it's a functional programming language thing. It allows you to programmatically manipulate the language, that is, call and manipulate functions. See [this chapter](http://adv-r.had.co.nz/Functional-programming.html) of Hadley Wickham's Advanced R book for more information. – tmpname12345 Jan 12 '16 at 18:09