首页 > 解决方案 > R闪亮基于使用反应的条件输入读取特定的csv文件

问题描述

我正在尝试创建一个闪亮的应用程序,它采用csv文件并从中提取特定信息。当我加载一个文件并运行我的代码时,一切正常。但现在我希望用户能够选择要分析的 CSV 文件,因为每个文件都包含不同的书籍。这是我到目前为止的代码

library("shiny")
library("tidyverse")
library("stringr")

## Define UI
ui <- fluidPage( 

    titlePanel("Find words in the text"),

  ## Sidebar panel
    sidebarLayout(
        sidebarPanel(

             ## Textual input
            selectInput("source", "Choose Text",
                         choices = c("Book 1" = 1,
                                     "Book 2" = 2),
                         selected = "Book 1"),

            textInput("word", "Insert words", value = ""),

            helpText("Type the word or words (separated by comma)\n
                  that you would like to find"),
            submitButton(text = "Search", icon("refresh")),
            br(), 

            textOutput("text")
        ),

        ## Main panel for outputs
        mainPanel(            
            tabsetPanel(
                tabPanel("Main",
                         tableOutput("view")),
                tabPanel("Summary",
                         tableOutput("summary"))
            )
        )
    )
)

server <- function(input, output) {

    k <- reactive({
             k <- ifelse(input$source == 1,
                              read_delim("book1.csv", delim = ";"),
                              read_delim("book2.csv", delim = ";"))
    })

    output$view <- renderTable({
        k %>%
            filter(str_detect(text,
                              str_split(input$word, ",")[[1]]))
    })

    output$text <- renderText({
        palabras <- str_split(input$word, ",")[[1]]
        n.times <- select(k, text) %>%
            str_count(c(palabras))
        paste("The word ", c(palabras),
              " appeared: ", n.times, " times")
    })


    output$summary <- renderTable({
        p <- str_replace_all(input$word, ",", "|")
        k %>%
            extract(col = text,
                    into = "Keyword",
                    regex = str_c("(",p, ")"),
                    remove = T, convert = T) %>%
            na.omit()
    })
}

## Create Shiny app
shinyApp(ui = ui, server = server)

我还尝试将开头的部分k <- reactive({k我想拥有我的书的小标题在哪里)更改为我首先加载每本书然后将其发送到的部分k,就像这样

book1 <- read_delim("book1.csv", delim = ";")
book2 <- read_delim("book2.csv", delim = ";")

k <- reactive ({
         k <- ifelse(input$source == 1,
                     book1,
                     nook2)
              })

我已经尝试了几天使用教程和stackoverflow,但我找不到真正适合我的东西。我尝试了几种不同的方法,但显然我在功能上做错了reactive。如果有人可以帮助我解决它并解释我的错误,我将非常感激,因为这是我的第一个 Shiny 应用程序。

仅作记录:如果我删除与reactive零件相关的所有内容并仅将文件加载到k类似的内容中,k <- read_delim("book1.csv", delim = ";")那么我的应用程序可以完美地进行字数统计。

标签: rshinyreactive

解决方案


推荐阅读