rstudio / shinymeta

Record and expose Shiny app logic using metaprogramming
https://rstudio.github.io/shinymeta
223 stars 14 forks source link

Print infix operators in a more familiar order #82

Open etiennebacher opened 4 years ago

etiennebacher commented 4 years ago

In the example below, the code given by shinymeta works but it is different of what I expected.

Although the code obtained works, I'm worried it confuses the users when they try to see the code behind the shiny app. Is there a way to display infix operators in a more familiar way?

library(dplyr)
library(shiny)
library(shinymeta)

ui <- fluidPage(
  selectInput("choice", "Select a column", choices = c("mpg", "drat", "hp"), multiple = F),
  outputCodeButton(tableOutput("table"), label = "Show code")
)

server <- function(input, output, session) {

  data1 <- metaReactive({
    data <- head(mtcars) 
    data$time <- rep(seq(1:3)) 
    data$ID <- rep(c("A", "B"), each = 3)
    data
  })

  data2 <- metaReactive({
    lagged_name <- paste0(..(input$choice), "_lagged")
    ..(data1()) %>%
      select(ID, time, sym(..(input$choice))) %>%
      group_by(ID) %>%
      mutate(!!lagged_name := lag(!!sym(..(input$choice))))
  })

  output$table <- metaRender(renderTable, {
    ..(data2())
  })

  observeEvent(input$table_output_code, {
    code <-  expandChain(data1(), data2())
    displayCodeModal(code)
  })   

}

shinyApp(ui, server)

Not sure at all if this is the right place to post this, sorry if it's not (also asked on RStudio Community)

jcheng5 commented 6 months ago

Surprising, this seems to be the behavior of R's deparse:

> deparse(quote(a + b))
[1] "a + b"
> deparse(quote(a := b))
[1] "`:=`(a, b)"

Oh, because := comes from rlang, not R. Errrrrgh... will have to think about this.

etiennebacher commented 6 months ago

I completely forgot about this issue. I thought rlang::expr_deparse() might do the trick but it doesn't seem to work with more complex expressions:

library(rlang)

expr_deparse(quote(a + b))
#> [1] "a + b"
expr_deparse(quote(a := b))
#> [1] "a := b"

lagged_name = "foo"
expr_deparse(dplyr::mutate(mtcars, !!lagged_name := lag(!!sym("mpg"))))
#> [1] "<df[,12]>"
etiennebacher commented 6 months ago

My bad, the last expression should have been in quote():

library(rlang)

expr_deparse(quote(a + b))
#> [1] "a + b"
expr_deparse(quote(a := b))
#> [1] "a := b"

lagged_name = "foo"
expr_deparse(quote(dplyr::mutate(mtcars, !!lagged_name := lag(!!sym("mpg")))))
#> [1] "dplyr::mutate(mtcars, !!lagged_name := lag(!!sym(\"mpg\")))"

I don't know the internals of shinymeta so can't help further, but I just wanted to correct my previous post