1

Using R shiny, I am developing a simple app that allows user to input data from a Rdata file. I want the app to load the data, show the names of numeric variables in a select input field, and after the user selected one of variables do some analysis. But I can not get it working. In the code provided I obtain two outputs: summary, which works fine, and the MEAN of the selected variable which I can not get work.

server.R

library(shiny)
library(shinydashboard)
library(data.table)
library(DT)

shinyServer(function(input, output) {


####   DATA LOAD
df <- reactive({
 df <- input$datafile
 if (is.null(df)) {
  # User has not uploaded a file yet
  return(NULL)
 }
 objectsLoaded <- load(input$datafile$name) 
 # the above returns a char vector with names of objects loaded
 df <- eval(parse(text=objectsLoaded[1])) 
 # the above finds the first object and returns it
 df<-data.table(df)

})


####   SELECTS

num <- reactive({  
 num <- sapply(df(),is.numeric)
 num <- names(num)
})

output$var_num <- renderUI({
 vector.num <- as.vector(num())
 selectInput("var_num", "Select Variables :", as.list(vector.num),  multiple = FALSE)
 }) 



####   OUTPUTS 
### SUMMARY 
output$summary_num <-renderDataTable({
  x<-t(sapply(df(), summary))
  x<-as.data.frame(x)
  x<-setDT(x, keep.rownames = TRUE)[]
  colnames(x) <- c("Variable","Mínimo","1er Quartil", "Mediana", "Media", "3er Quartil","Máximo")
  datatable(x)

 })

### MEAN OF SELECTED VAR  
output$test <-renderPrint ({
  if(is.null(df()))
  return()
  dat<- df()
  dat <- dat[,num(), drop = FALSE]
  mean(dat[,input$var_num])
  })  
})

UI.R

dashboardPage(
  dashboardHeader(title = "TITLE", titleWidth = 500),
  dashboardSidebar(disable = TRUE), #---> fin SIDEBAR
  dashboardBody(
    fluidRow(
      box(width=12,  status = "primary",
        tabsetPanel(
          tabPanel("Test",
                   fileInput("datafile", label = h3("File input")),
                   uiOutput("var_num"),
                   br(),hr(),br(),

                   fluidRow(column(width=4, uiOutput("var_caracter"),textOutput("test"))),
                   br(),hr(),br(),

                   fluidRow(column(width=8, "Variables Numericas", dataTableOutput("summary_num")))
                   )

            ) # fin tabsetPanel
          ) # fin box
      )# fin fluidRow
    )# fin dashboardBody
 )# fin dashboardPage

When I run the app everything goes fine (select input, summary, etc) except the calculation and printing of the MEAN of the selected variable. I guess for some reason the subsetted dataframe is empty, but I do not know why... Any help will be great! Thanks in advance.

6
  • This doesn't speak to your question, but why are you sapplying is.numeric and then just taking the names? and then the reactive isn't actually returning anything... that's confusing. Commented Dec 27, 2015 at 20:28
  • But th use of sapply works fine, as is indicated by the select input that is filled only with numeric vars... The problem is passing the variable name selected for use in other analysis... Yes is confusing. Commented Dec 27, 2015 at 20:37
  • I was talking about this: num <- reactive({ num <- sapply(df(),is.numeric) num <- names(num) }) this doesn't return anything and the operation itself doesn't make sense. Commented Dec 27, 2015 at 20:46
  • I am no so experienced in R or Shiny, but what I tried to do with that lines of code is to obtain the names of the numeric variables of the loaded data. I use it in the select input "var_num" and is rendered in the UI and works fine. In fact it is not empty, so it is working. I do not see why you say it is returning anything .... Commented Dec 27, 2015 at 20:53
  • Okay, if you want that, then what you want is names(df())[sapply(df(),is.numeric)] Commented Dec 27, 2015 at 21:29

1 Answer 1

1

I get it working. The solution was to define the dataset I used as.data.frame:

### MEAN OF SELECTED VAR  
  output$test <-renderPrint ({
    if(is.null(df()))
      return()
    dat<- as.data.frame(df()) ## THIS IS THE CORRECTION
    dat <- dat[,num(), drop = FALSE]
    mean(dat[,input$var_num])
 })  

I do not really understand why... The reactive file df() was defined as data.table and dat shoul inherit that, but for some reason it was necesary an explicit definition as dataframe.

Sign up to request clarification or add additional context in comments.

2 Comments

data.table has different syntax from data.frame. dat[,num(), drop = false] means something completely different between the two.
Thanks for the explanation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.