Как очистить данные CSV после загрузки в приложение Shiny - PullRequest
0 голосов
/ 30 ноября 2018

Пожалуйста, помогите!

Я пытаюсь создать блестящее приложение с целью классификации данных, загружаемых из файла CSV.Как мне успешно создать DataFrame из CSV-файла (который загружен), чтобы я мог двигаться дальше и очищать / анализировать его.

Пожалуйста, смотрите код:

library(shiny)
library(lubridate)
library(utils)
library(dplyr)
library(tidytext) 

ui <- (pageWithSidebar(
  headerPanel("CSV File Upload Demo"),

  sidebarPanel(
    #Selector for file upload
    fileInput('datafile', 'Choose CSV file',
              accept=c('text/csv', 'text/comma-separated-values,text/plain')),
    #These column selectors are dynamically created when the file is loaded
    uiOutput("fromCol"),
    uiOutput("toCol"),
    uiOutput("amountflag"),
    #The conditional panel is triggered by the preceding checkbox
    conditionalPanel(
      condition="input.amountflag==true",
      uiOutput("amountCol")
    )

  ),
  mainPanel(
    tableOutput("filetable")
  )
))

Пожалуйста, сообщите, следует ли использовать Reactive

server <- (function(input, output) {

  #This function is repsonsible for loading in the selected file
  filedata <- reactive({
    infile <- input$datafile
    if (is.null(infile)) {
      # User has not uploaded a file yet
      return(NULL)
    }

    dataframe <- reactive({
      readr::read_csv(infile()$datapath)
    })

  # Clean data by whole-case removal of missing cells (either NAs or "nan")
  # Remove the rows which have NAs
  myDataClean2 = dataframe[complete.cases(dataframe),]

  # In order to turn it into a tidy text dataset, we first put the data into a data frame:
  text_df <- data_frame(myDataClean2$text,myDataClean2$title,myDataClean2$author,myDataClean2$id,myDataClean2$label)
  names(text_df) <- c("text","title","author","id","label")

  # Within the tidy text framework, we break both the text into individual tokens and transform 
  # it to a tidy data structure. To do this, we use tidytextâs unnest_tokens() function.
  tidy_text_df <- text_df %>%
    unnest_tokens(word, text)

     #This previews the CSV data file
  output$filetable <- renderText({
    tidy_text_df()

  })
  })
    })



# Run the application 
shinyApp(ui = ui, server = server)

1 Ответ

0 голосов
/ 30 ноября 2018

Вы смешиваете реактивные блоки.Ваш filedata должен заканчиваться чем-то, что выводит ваши данные, скорее всего, выводом из unnest_tokens(word, text).(Должны быть выведены все данные, которые вас интересуют, я думаю, что эта строка делает.) Оттуда ваш output$filetable должен быть вне реактивного блока filedata, сам по себе.И он должен использовать filedata(), а не tidy_text_df (который недоступен за пределами первого реактивного блока).

Попробуйте это:

server <- (function(input, output) {

  #This function is repsonsible for loading in the selected file
  filedata <- reactive({
    infile <- input$datafile
    if (is.null(infile)) {
      # User has not uploaded a file yet
      return(NULL)
    }

    dataframe <- reactive({
      readr::read_csv(infile()$datapath)
    })

    # Clean data by whole-case removal of missing cells (either NAs or "nan")
    # Remove the rows which have NAs
    myDataClean2 = dataframe[complete.cases(dataframe),]

    # In order to turn it into a tidy text dataset, we first put the data into a data frame:
    text_df <- data_frame(myDataClean2$text,myDataClean2$title,myDataClean2$author,myDataClean2$id,myDataClean2$label)
    names(text_df) <- c("text","title","author","id","label")

    # Within the tidy text framework, we break both the text into individual tokens and transform 
    # it to a tidy data structure. To do this, we use tidytextâs unnest_tokens() function.
    text_df %>%
      unnest_tokens(word, text)
  })

  #This previews the CSV data file
  output$filetable <- renderText({
    filedata()
  })
})
...