Troubles using "selectInput" to select variable with dplyr

392 views
Skip to first unread message

Ignacio Martinez

unread,
Sep 8, 2015, 11:30:02 AM9/8/15
to shiny-...@googlegroups.com
Hi,

This very simple example illustrates the problem that I'm having:

    df1 <-
      structure(
        list(
          `long name 1` = c(NA, 18L, NA, 24L, 21L, NA, NA,NA, NA, NA),
          `long name 2` = c(NA, 24L, NA, 35L, 23L, NA, NA,NA, NA, 25L)
        ), class = c("tbl_df", "data.frame"),
        row.names = c(NA,-10L), .Names = c("long name 1", "long name 2")
      )
    
    server <- function(input, output) {
      output$txt1 <- renderText({
        df1 %>% summarise(y1 = mean(input$select,na.rm = T)) %>%
          as.character()
      }) 
    }
    
    ui <- fluidPage(sidebarLayout(sidebarPanel(
      width = 3,
      selectInput(
        "select", label = h3("Variable"),
        choices = list("long name 1" = "long name 1",
                       "long name 2" = "long name 2"),
        selected = 1
      )
    ),
    mainPanel(h3(textOutput(
      "txt1"
    )))))
    
    shinyApp(ui = ui, server = server)

The only solution that I can think is to use a series of if statements instead of using input$select directly in summarise. Any suggestions?

Thanks!

msquatrito

unread,
Sep 9, 2015, 7:01:07 AM9/9/15
to Shiny - Web Framework for R
Hi, 
you could use  `substitute` and `eval`, such as:

server <- function(input, output) {
  output$txt1
<- renderText({

    txt
<- substitute(df1 %>%
                        summarise
(y1 = mean(sel,na.rm = T)) %>%
                       
as.character(),
                      list
(sel = as.name(input$select)))
    txt
<- eval(txt)
 
})
}


Best,
Massimo

Winston Chang

unread,
Sep 9, 2015, 1:13:52 PM9/9/15
to msquatrito, Shiny - Web Framework for R
You can use the `summarise_` function when you want to use variables in dplyr functions. Other dplyr functions also have a version with a trailing underscore. For example:

library(dplyr)

# The usual way of using dplyr
mtcars %>%
  group_by(cyl) %>%
  summarise(meanwt = mean(wt))


# Passing in strings in variables
group <- "cyl"
var <- "mean(wt)"
mtcars %>%
  group_by_(group) %>%
  summarise_(meanwt = var)



--
You received this message because you are subscribed to the Google Groups "Shiny - Web Framework for R" group.
To unsubscribe from this group and stop receiving emails from it, send an email to shiny-discus...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/shiny-discuss/a5453899-bbb0-4003-9a13-925268eb21aa%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages