R Shiny. No applicable method for 'mutate' applied to an object of class "c('reactiveExpr', 'reactive', 'function')"

Viewed 1603

I am trying to create a very simple Shiny app that could let a user select a set of tables and see which variables are shared by those tables.

My input data (named "df" in my code below) looks like this:

Tables Variables
tabla_1 A
tabla_1 Z
tabla_1 Y
tabla_1 V
tabla_1 B
tabla_2 H
tabla_2 B
tabla_2 A
tabla_2 U
tabla_3 U
tabla_3 S
tabla_3 M
tabla_4 U
tabla_4 A
tabla_4 B
tabla_4 V
tabla_4 Q
tabla_4 O
tabla_4 F

If the user selected all the tables available to compare them, the output would have to look like this (mytable1 in my code below):

Variables tabla_1 tabla_2 tabla_3 tabla_4
A Yes Yes No Yes
Z Yes No No No
Y Yes No No No
V Yes No No Yes
B No Yes No Yes
H No Yes No No
U No Yes Yes Yes
S No Yes Yes No
M No No Yes No
Q No No No Yes
O No No No Yes
F No No No Yes

Right now my code looks like this:

library(shiny)
library(dplyr)



ui <- fluidPage(
  title = "Compare Data Tables",
  
    sidebarPanel(
        
        checkboxGroupInput("show_tables", "Tables to compare",
                           unique(df$Tables), selected = unique(df$Tables)
                           
                           ),
        
        mainPanel("comparison", DT::dataTableOutput("mytable1"))))

server <- function(input, output) {
  
  
  
  filter1 <- reactive({subset(df, Tables == input$show_tables)})
  
  result<-filter1 %>% 
           mutate(n = "Yes")%>%
           pivot_wider(names_from = Tables, values_from = n, values_fill = list(n = "No"))
  
  output$mytable1 <- DT::renderDataTable({
    DT::datatable(result)
  })
  
}

shinyApp(ui, server)


After I run that I get this message:

Error in UseMethod("mutate") : no applicable method for 'mutate' applied to an object of class "c('reactiveExpr', 'reactive', 'function')"

I am not sure what might be wrong. Is it that I cannot use the mutate function to a reactive object. If so, what could I use instead to get the same output?

Thanks a lot for any suggestions.

1 Answers

We could change the server part to

server <- function(input, output) {
  
  
  
  result <- reactive({
    
    req(input$show_tables)
    tmp <- subset(df, Tables %in% input$show_tables)
  
  tmp %>% 
    dplyr::mutate(n = "Yes")%>%
    tidyr::pivot_wider(names_from = Tables, values_from = n, values_fill = list(n = "No"))
  })
  output$mytable1 <- DT::renderDataTable({
    DT::datatable(result())
  })
  
}

shinyApp(ui, server)

-output

enter image description here

Related