Multiple modules

62 views
Skip to first unread message

Olaia Olazar

unread,
May 18, 2017, 10:08:05 AM5/18/17
to Shiny - Web Framework for R
Hi!

As my code is getting longer and longer, I've decided to add modules but I'm having problems :(
Here is a simple part of my code where you first select a file and then, on one hand, the program shows you all the data in a datatable (inside a tabPanel called "Datos"), and on the other hand plots y="Gt", x="Tiempo" (in another tabPanel called "Salida dia")

I've used a module called "dataTable.R". I would like to be able to use another module which would have all the code which is in charge of the plots, but I can't get it.

Thank you!!! :)

<< ui.R >>
library(shiny)
library(DT)
library(shinydashboard)
library(ggplot2)
library(shinythemes)
library(dplyr)
library(zoo)
library(markdown)
source("dataTable.R")
colnames<-c("Scan","Tiempo","Global","Difusa","Directa1","Directa2",
            "DFRCen_V","DFRCen_T","Cli_V3","Cli_V2","Cli_V1","BAR")
conf<-checkboxGroupInput('columnas',"Escoge las columnas de la tabla",
                         choices=colnames,selected=colnames[-c(1,9,10)])
alphacen<-numericInput("alphacen",label=h5(strong("Alpha CENER")),
                       value=0.00015,step=0.00001,width='80%')
alphacli<-numericInput("alphacli",label=h5(strong("Alpha Cliente")),
                       value=0.0000,step=0.00001,width='80%')
clit<-numericInput("clit",label=h5(strong("Temperatura de la celula del cliente")),
                   value=25,step=0.25,width='80%')
shinyUI(fluidPage(
  dashboardPage(
    dashboardHeader(),
    dashboardSidebar(
      sidebarMenu(
        csvFileInput("datafile", "User data (.csv format)"),
        menuItem(strong("Dia 1"),tabName="dia1")
      )
    ),
    dashboardBody(
      tabItems(
          tabItem(tabName="dia1",
                  tabsetPanel(
                    tabPanel("Configuracion",icon=icon("cog"),
                             column(width=4,
                                    box(conf,width=NULL,status="warning")),
                             column(width=4,
                                    box(clit,width=NULL,status="warning")
                             ),
                             column(width=4,
                                    box(alphacli,width=NULL,status="warning"),
                                    box(alphacen,width=NULL,status="warning")
                             )),
                    tabPanel("Datos",icon=icon("table"),
                             dataTableOutput("tb")),
                    tabPanel("Salida dia",icon=icon("area-chart"),
                             column(width=12,
                                    box(title=strong("Gt-Tiempo"),solidHeader=FALSE,
                                        status="success",collapsible=TRUE,
                                        plotOutput("g1",height=200))
                             ))
                  )
        )
      ))
))
)


<< server.R >> 
library(shiny)
library(DT)
library(shinydashboard)
library(ggplot2)
library(dplyr)
library(zoo)
source("dataTable.R")
colnames<-c("Scan","Tiempo","Global","Difusa","Directa1","Directa2",
            "DFRCen_V","DFRCen_T","Cli_V3","Cli_V2","Cli_V1","BAR")
conf<-checkboxGroupInput('columnas',"Escoge las columnas de la tabla",
                         choices=colnames,selected=colnames[-c(1,9,10)])
alphacen<-numericInput("alphacen",label=h5(strong("Alpha CENER")),
                       value=0.00015,step=0.00001,width='80%')
alphacli<-numericInput("alphacli",label=h5(strong("Alpha Cliente")),
                       value=0.0000,step=0.00001,width='80%')
clit<-numericInput("clit",label=h5(strong("Temperatura de la celula del cliente")),
                   value=25,step=0.25,width='80%')
shinyServer(function(input, output, session) {
  datafile<-callModule(csvFile,"datafile")
 
  output$tb<-renderDataTable({
      DT::datatable(datafile() %>%select_(.dots=input$columnas),
              extensions='FixedColumns',
              options=list(searching=FALSE,
                           lengthMenu=list(c(10,25,50,-1),
                                           c('10','25','50','Todo')),
                           autoWidth=TRUE,scrollX=400,
                           scrollY=400,fixedColumns=3
                           ))
  })
 
  grafica1<-reactive({
    df<-datafile()
    Gt<-((df$Difusa)+(df$Directa1))
    df<-mutate(df,valido=(df$Difusa/Gt>0.1)&(df$Difusa/Gt<0.3)&(Gt>800)&(Gt<1200))
    g1<-qplot(df$Tiempo,Gt,data=df,col=as.factor(valido))+
      geom_point()+xlab("Tiempo")+ylab("Gt")
    g1<-g1+geom_smooth(method='lm')
    g1
  })
 
  output$g1<-renderPlot({
    grafica1()
  })
})

<< dataTable.R >>
# Module UI function
csvFileInput <- function(id, label = "CSV file") {
  # Create a namespace function using the provided id
  ns <- NS(id)
 
  tagList(
    fileInput(ns("file"), label))
}
# Module server function
csvFile <- function(input, output, session) {
 
  colnames<-c("Scan","Tiempo","Global","Difusa","Directa1","Directa2",
              "DFRCen_V","DFRCen_T","Cli_V3","Cli_V2","Cli_V1","BAR")
  conf<-checkboxGroupInput('columnas',"Escoge las columnas de la tabla",
                           choices=colnames,selected=colnames[-c(1,9,10)])
  alphacen<-numericInput("alphacen",label=h5(strong("Alpha CENER")),
                         value=0.00015,step=0.00001,width='80%')
  alphacli<-numericInput("alphacli",label=h5(strong("Alpha Cliente")),
                         value=0.0000,step=0.00001,width='80%')
  clit<-numericInput("clit",label=h5(strong("Temperatura de la celula del cliente")),
                     value=25,step=0.25,width='80%')
 
  # The selected file, if any
  userFile <- reactive({
    # If no file is selected, don't do anything
    input$file
  })
 
  # The user's data, parsed into a data frame
  datafile <- reactive({
    read.csv(userFile()$datapath,
             sep=",",
             skip=50,
             col.names=colnames,
             fileEncoding="UCS-2LE")
  })
 
  # Return the reactive that yields the data frame
  return(datafile)
}


30.3095.0 1_3_2017 06_58_57 1.csv

Joe Cheng

unread,
May 18, 2017, 1:26:09 PM5/18/17
to Olaia Olazar, Shiny - Web Framework for R
Those input widgets (conf, alphacen, alphacli, clit) should not be defined in the module server function. They should be part of a module UI function (the csvFileInput one? a new plotting-related one? I'm not sure what your intentions are here).

It sounds like your question is how to pass the reactive data that is generated by the csvFile module, to another module that does plotting. You can do that by having your plot module's server function take an additional argument, e.g. `datafile`, and then when invoking that module using callModule, pass the reactive that's returned from csvFile.

i.e. in your app's top-level server function:

datafile <- callModule(csvFile, "datafile")
callModule(plotModule, "plot", datafile)

Note that you pass it without parentheses--you're passing the actual reactive expression object, not just the current value of the reactive expression object. Then in your plotModule code, you can use datafile() inside of reactive expressions or outputs to get the data.

--
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/82b8c630-aa4a-40d3-9237-7fa6c5f0fd3e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Olaia Olazar

unread,
May 19, 2017, 5:18:36 AM5/19/17
to Shiny - Web Framework for R, olaia...@gmail.com
First of all, thank you for answering so fast.
But I still don't get it...
I have created another module, called "plotModule.R" which should read the datafile and plot a simple plot, but I get the next error: "Error: could not find function "grafica1"".

Does anyone know why??
Thank you :)

<< ui.R >>

library(shiny)
library(DT)
library(shinydashboard)
library(ggplot2)
library(shinythemes)
library(dplyr)
library(zoo)
library(markdown)
source("dataTable.R")
source("plotmodule.R")


<< server.R >>

source("plotmodule.R")
colnames<-c("Scan","Tiempo","Global","Difusa","Directa1","Directa2",
            "DFRCen_V","DFRCen_T","Cli_V3","Cli_V2","Cli_V1","BAR")
conf<-checkboxGroupInput('columnas',"Escoge las columnas de la tabla",
                         choices=colnames,selected=colnames[-c(1,9,10)])
alphacen<-numericInput("alphacen",label=h5(strong("Alpha CENER")),
                       value=0.00015,step=0.00001,width='80%')
alphacli<-numericInput("alphacli",label=h5(strong("Alpha Cliente")),
                       value=0.0000,step=0.00001,width='80%')
clit<-numericInput("clit",label=h5(strong("Temperatura de la celula del cliente")),
                   value=25,step=0.25,width='80%')
shinyServer(function(input, output, session) {
  datafile<-callModule(csvFile,"datafile")
  callModule(plotModule, "grafica1", datafile)

 
  output$tb<-renderDataTable({
      DT::datatable(datafile() %>%select_(.dots=input$columnas),
              extensions='FixedColumns',
              options=list(searching=FALSE,
                           lengthMenu=list(c(10,25,50,-1),
                                           c('10','25','50','Todo')),
                           autoWidth=TRUE,scrollX=400,
                           scrollY=400,fixedColumns=3
                           ))
  })
 
<< plotModule.R >>

plotModule<-function(input,output,session,datafile){
  datafile<-callModule(csvFile,"datafile")
 
  grafica1<-reactive({
    g1<-plot(x=datafile$Tiempo,y=datafile$Global)
    g1
  })
 
  return(grafica1)
}

Joe Cheng

unread,
May 19, 2017, 1:23:30 PM5/19/17
to Olaia Olazar, Shiny - Web Framework for R
Can you do me a favor that will make this much easier?

1. Upload your code to a gist (gist.github.com), splitting the gist into files as they are on the filesystem.
2. Include in the gist some sample data.

There are several problems in your code that are easier to show a diff than to explain.

Olaia Olazar

unread,
May 20, 2017, 5:46:53 AM5/20/17
to Shiny - Web Framework for R, olaia...@gmail.com
I just did it. This is the URL for the gist:


If you need anything else, please ask me, I'll try to help you as much as possible. 
Thank you!! :)

Olaia Olazar

unread,
May 23, 2017, 10:08:41 AM5/23/17
to Shiny - Web Framework for R, olaia...@gmail.com
Dear Joe,

I'm sure that you are really busy, but I wanted to know wheter you are working on my code or not as I have to deliver it this week. :|

Waiting for your answer,
Thank you
Olaia

Joe Cheng

unread,
May 23, 2017, 1:21:41 PM5/23/17
to Olaia Olazar, Shiny - Web Framework for R
There are several problems:
  1. Minor nit: userFile reactive is just "input$file", I would change this to "req(input$file)"(see https://shiny.rstudio.com/articles/req.html for explanation)
  2. In plotModule function
    1. you are both taking in a datafile argument, and then also calling the csvFile module and assigning the result to datafile. I suspect you just forgot to remove the latter?
    2. In the grafica1 reactive, you need to use `datafile()` instead of `datafile` to access the data.
    3. That said, you should never plot inside of a reactive expression like you are in grafica1. The reason is that reactives cannot be relied on for side effects. I go into this in my Effective Reactive Programming tutorials here: https://www.rstudio.com/resources/webinars/shiny-developer-conference/ Instead, you should give the plotModule a plotModuleUI, and put the plotOutput in there; then instead of a grafica1 reactive you can directly do `output$plot <- renderPlot({ plot(x=datafile()$Tiempo, ...`
  3. After making these fixes I still did not see any data in the data frame--I suspect something's wrong with the CSV reading logic but I couldn't make sense out of your data file.

Olaia Olazar

unread,
May 24, 2017, 4:13:34 AM5/24/17
to Shiny - Web Framework for R, olaia...@gmail.com
You are right. I don't know what was wrong with the CSV file.
I attach another file, but this one Works fine in case you want to try it.
Thank you :)
30.3095.0 1_3_2017 06_58_57 1.csv

Olaia Olazar

unread,
May 24, 2017, 6:12:11 AM5/24/17
to Shiny - Web Framework for R, olaia...@gmail.com
I've changed all you suggested but I still don't know how to get it to plot the graph in the "Salida dia" tabPanel from ui.R
Any idea why?
I have uploaded the new code on a new gist. This is the URL:


Thank you :)
30.3095.0 1_3_2017 06_58_57 1.csv

Joe Cheng

unread,
May 24, 2017, 3:20:18 PM5/24/17
to Olaia Olazar, Shiny - Web Framework for R
In plotModule, g1<-renderPlot should be output$g1<-renderPlot

In your UI, don't do callModule(plotModuleUI,"g1"); that is only for server functions. For UI, you do plotModuleUI("g1"). Sorry, I know it's a bit complicated.

Olaia Olazar

unread,
May 25, 2017, 2:47:13 AM5/25/17
to Shiny - Web Framework for R, olaia...@gmail.com
Okay, I think I get it now.
I'm very grateful. You do a really good job at this group, as you help a lot of people who are lost with RStudio like me.
Thank you!!! :)
Reply all
Reply to author
Forward
0 new messages