【问题标题】:R Shiny: Read CSV and save in a variable with dplyr and ggplotR Shiny:读取 CSV 并使用 dplyr 和 ggplot 保存在变量中
【发布时间】:2018-08-21 18:50:21
【问题描述】:

我正在尝试将 fileInput 添加到我的 R Shiny 程序中,用户可以将他们自己的 CSV/Excel 文件添加到其中,但是,我遇到了一些问题。

如果我直接从我的 PC 运行代码读取 CSV(没有 fileInput),我没有问题,但任何时候我尝试输入它都会出错。

我做了一些研究并试图复制我在网上看到的内容,但他们的解决方案对我不起作用。我已经看过this postthis post,但是他们的方法不起作用。或者我还是做错了什么。

ui <- fluidPage(

  theme = 'custom.css',

  dashboardPage(
    dashboardHeader(title = 'Student Grades'),
    dashboardSidebar(
      fileInput(inputId = 'file', label = 'Select a file...'),
      selectInput(inputId = 'periodVar', 
                  label = 'Select Period',
                  choices = unique(grades$Period)),
      uiOutput('secondSelection'),
      dataTableOutput('individualSummary'),
      img(src='lhimg.JPG', width = '100%')
                    ),

    dashboardBody(
      useShinyjs(),
      tabsetPanel(
        tabPanel(
          'Test',
          tableOutput('contents')
                ),
        tabPanel(
          'Graph',
          plotOutput('individualGraph')
                )
          )
    )
  )
)

server <- function(input, output, session) {

  # grades <- eventReactive(input$file, {
  #   read.csv(input$file$datapath)
  # })

  grades2 <- reactive({
    inFile <- input$file
    if (is.null(inFile))
      return(NULL)
    myTbl <- read.csv(inFile$datapath)
    return(myTbl)
  })

  # observe({
  #   grades2 = input$file
  #   if (is.null(file)) {
  #     return(NULL)
  #   }
  #   grades2 = read.csv(grades2$datapath)
  # })

  tidyGrades <- function(data){
    data %>% 
      gather(key = Type, value = Grade, (c('Test', 'Quiz', 'Homework')), na.rm = T) %>% 
      arrange(Period, Student,Date, Type) %>% 
      mutate(Weight = ifelse(Type == 'Homework', 30, 
                             ifelse(Type == 'Quiz', 20, 50)),
             Date = mdy(Date))
  }

  weightedMeanDf <- tidyGrades(grades2)

我的代码有一个小的 sn-p。如果需要,我可以发布整个内容,但我不想在寻求帮助时使其难以阅读。 weightedMeanDf 只是我需要做的一件事,但我还需要生成一些其他图表和表格。注释代码是我根据在线解决方案尝试过的不同方法。我得到的最接近的是在服务器函数中使用未注释的代码(第一个反应)函数。

但是我得到了这个错误:

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

我真的很茫然,现在我的想法已经不多了。也许我的做法完全错误。也许最好的方法是对创建的每个绘图和数据框使用反应函数?我觉得这只会减慢一切,而不是读取 csv 文件一次,然后根据第一次读取生成图形和绘图?

【问题讨论】:

  • 好吧,grades2 是一个反应式表达。它不是一个data.frame。如果你想得到那个反应式表达式的值,你应该使用grades2()。但目前尚不清楚您如何使用weightedMeanDf。这很可能也是一种反应性表达。 weightedMeanDf &lt;- reactive({ tidyGrades(grades2()) })
  • 我发现了。我现在实际上可以在导入文件后打印出一个数据表。但我的问题是将它与 ggplot 和 dplyr 一起使用。有没有办法将 renderTable 对象转换为数据框?
  • 好吧,你必须将 data.frame 传递给 renderTable。只需将该数据源设为反应性对象,然后您就可以在 renderTable 和 renderPlot 或任何其他您喜欢的对象中使用相同的对象。看起来您的问题可能没有很好地描述您所面临的问题。
  • 你可能是对的。我很抱歉没有说清楚。但我认为你的第一条评论回答了我的问题。我没有使用 Grades2() 并没有使用括号。我还有很多工作要弄清楚来改变我的程序,但我认为我现在应该能够得到它。非常感谢你帮助我!

标签: r shiny


【解决方案1】:

这个怎么样???

library(shiny)
library(digest)

# Create data to read
write.csv(file="~/iris.csv",iris)

shinyApp(ui=shinyUI(
  fluidPage(
    sidebarLayout(
      sidebarPanel(
        textInput("path","Enter path: "),
        actionButton("readFile","Read File"),
        tags$hr()
      ),
      mainPanel(
        tableOutput('contents')
      )))
),
server = shinyServer(function(input,output,session){
  file <- reactiveValues(path=NULL,md5=NULL,rendered=FALSE)

  # Read file once button is pressed
  observeEvent(input$readFile,{
    if ( !file.exists(input$path) ){
      print("No such file")
      return(NULL)
    }
    tryCatch({
      read.csv(input$path)
      file$path <- input$path
      file$md5  <- digest(file$path,algo="md5",file=TRUE)
      file$rendered <- FALSE
    },
    error = function(e) print(paste0('Error: ',e)) )
  })

  observe({
    invalidateLater(1000,session)
    print('check')

    if (is.null(file$path)) return(NULL)

    f   <- read.csv(file$path)
    # Calculate ckeksum
    md5 <- digest(file$path,algo="md5",file=TRUE)

    # If no change in cheksum, do nothing
    if (file$md5 == md5 && file$rendered == TRUE) return(NULL)

    output$contents <- renderTable({

      print('render')
      file$rendered <- TRUE
      f
    })
  })

}))

【讨论】:

  • 谢谢!这是一个很好的例子!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多