osbwh
osbwh

Reputation: 79

create new variable = existing variable + user input in r shiny

I'm developing an app for student results in my school.

I want to see the summary of fail vs pass after adding certain numbers to every student's grade.

An example below

library(shiny)
biology_num <- c(49,64,74,84)
biology_pass_fail <- ifelse(biology_num < 50, "Fail", "Pass")
First <- data.frame(cbind(biology_num,biology_pass_fail))
First$biology_num <- as.numeric(as.character(First$biology_num))

UI

ui <- fluidPage(
            selectInput("Subject",
                        "Choose Subject",
                         choices=list("biology")),
            numericInput("Addition","If we added","1"),
            tableOutput("table"),
            tableOutput("table2")
   )

Server Here is the issue

server <- shinyServer(function(input,output){
#Here I want to create a new dataframe that combines 
#the existing grades + the potential add      

New_biology <- reactive({
as.data.frame(cbind(New_biology_num+input$Addition))

New_biology$New_biology_pass_fail <- 
          as.factor(ifelse(New_biology$New_biology_num <50,"Fail","Pass"))
     })

output$table <- renderTable(as.table(summary(First$biology_pass_fail)))

output$table2 <- renderTable(as.table(summary({New_biology$New_biology_pass_fail()})))
    }
)

shinyApp(ui,server)

I then receive the error

object of type 'closure' is not subsettable

Something isn't right in the way I'm passing New_biology$New_biology_pass_fail to the output$table2 or maybe in the reactive formula.

Your guidance is really appreciated!

Upvotes: 0

Views: 1389

Answers (1)

cmaher
cmaher

Reputation: 5225

This seems to work the way you'd like it to:

library(shiny)
biology_num <- c(49, 64, 74, 84)
biology_pass_fail <- ifelse(biology_num < 50, "Fail", "Pass")

# DON'T call data.frame(cbind()). Just use data.frame()!
First <- data.frame(biology_num, biology_pass_fail)

ui <- fluidPage(
  selectInput("Subject",
              "Choose Subject",
              choices=list("biology")),
  numericInput("Addition","If we added","1"),
  tableOutput("table"),
  tableOutput("table2")
)

server <- function(input,output) {  

  New_biology <- reactive({
    New_biology_num <- biology_num + input$Addition

    data.frame(New_biology_num,
               New_biology_pass_fail = as.factor(ifelse(New_biology_num < 50, "Fail", "Pass")))    
  })

  output$table <- renderTable(First)

  output$table2 <- renderTable(New_biology())
}

shinyApp(ui, server)

It's important to know that reactive elements are functions. So if you create a reactive element (in this case New_biology), you need to invoke it as a function for it to return a value (i.e. New_biology()). If a reactive element returns a data.frame, and you want to access a specific column, you need to apply the accessor after the function invocation (e.g. New_biology()$New_biology_pass_fail).

Upvotes: 1

Related Questions