Import multiple csv file and merge, plot in R shiny

Viewed 33

I'm trying to build a Shiny App that loads multiple CSV which have the same format and merge as one. Finally, the goal is to make a plot from merged data.

It does work till the point of multiple CSV loading but fails to make a plot. I think the data is not properly merged inside of the code but not sure.

Here is an example of CSV and my code.

col1 col2 col3
1 437.2 0.12
2 435.1 0.11
3 434.4 0.95
library(shinydashboard)
library(ggplot2)
library(data.table)

#======================================================================
# UI
#======================================================================

ui = dashboardPage(
  
  #header
  dashboardHeader(
    title = 'Test_multiple csv import and plot'
  ),
  #sidebar
  dashboardSidebar(
    sidebarMenu(
      menuItem('Load log files',tabName = 'data_tab'),
      menuItem('Plot log files',tabName = 'plot_tab')
    )
  ),
  #body
  dashboardBody(
    #tabs
    tabItems(
    #tab for import
      tabItem(
        tabName = 'data_tab',
        fileInput('file','Data Loading(*.csv files)',multiple=T, accept = c('.csv'))
      ),
    #tab for plot  
      tabItem(
        tabName = 'plot_tab',
        plotOutput('plot')
      )
    )
  )
)

#======================================================================
# Server
#======================================================================

server = function(input,output){
  
  #load data
  vars = reactiveValues(df = NULL)
  observeEvent(input$file$datapath,{
    req(input$file)
    files= list.files(input$file$datapath)
    temp= lapply(files,fread)
    df = rbindlist(temp)
    vars$df <-as.data.frame(df)
  })
  
  #plot data
  output$plot = renderPlot({
    data.frame(time=vars$df[,1],emission=vars$df[,2]) %>%
      ggplot(aes(x=time, y=emission))+
      geom_line(color="red")+
      geom_point()
  })
  
}

#======================================================================
# Run App
#======================================================================

shinyApp(ui,server)
1 Answers

The first thing to note is that list.files lists the files in a given directory. You are not passing it a directory, you are passing it a list of files. So you just need to change the code to

observeEvent(input$file$datapath,{
    req(input$file)
    temp= lapply(input$file$datapath,fread)
    df = rbindlist(temp)
    vars$df <-as.data.frame(df)
  })

Secondly, you are constructing a dataframe from a dataframe here

output$plot = renderPlot({
    data.frame(time=vars$df[,1],emission=vars$df[,2]) %>%
      ggplot(aes(x=time, y=emission))+
      geom_line(color="red")+
      geom_point()
  })

You can just set the column names in your csv appropriatly then you can just pass in the dataframe directly as in vars$df %>% ..., but this isn't required to get your example to work.

Related