【问题标题】:Creating variables when importing data into the shiny-application, managing the received data在将数据导入闪亮应用程序时创建变量,管理接收到的数据
【发布时间】:2021-03-31 04:14:06
【问题描述】:

同志们!你好。 请帮帮我...有一些严重的误解。

假设我创建了这样的data.frame:

df<-data.frame(num = c(1:250),
           app_num =  sample(1:100, 250, replace=T),
           entrance=sample(1:4, 250, replace=T),
           gender=sample(c('m','f'), 250,replace=T),
           age= sample(1:100, 250, replace=T))

我将它保存为“*csv”格式,使用命令:

write.csv2(data_file,file = file.choose(new = T), row.names = FALSE, quote = FALSE)

好的。 现在我想创建一个闪亮的应用程序来显示和处理这些数据,比如他的:

    library("shiny")
    #to work with extra string functions
    library("stringr") 
    library("data.table") 
    library("readr")

    # Define UI for application that draws a histogram
    ui <- fluidPage(
      titlePanel(h2(strong("Analysis of the composition and structure of residents"),
                 align = "center")),
      fileInput(
        inputId="fileInput",
        label="Choose file",
        multiple = FALSE,
        accept = ".csv",
        width = '100%',
        buttonLabel = "Choosing ...",
        placeholder = "No files selected yet"
      ),
      sidebarPanel(
        checkboxGroupInput(inputId="gender", label = "Choosing a gender feature:",
          choices = c("Men" = "m",
                      "Women" = "f"),
          selected= c("Men" = "m",
                      "Women" = "f")),
        sliderInput(inputId = "age", label = "Indicate the age group:",
                    min = 1, max = 100, value = c(1, 100)),
        selectInput(
          inputId = "group",
          label="Indicate the entrance",
          choices=c(1:4),
          selected = c(1:4),
          multiple = TRUE,
          selectize = TRUE,
          width = NULL,
          size = NULL
        )
      ),
      mainPanel(
        navbarPage("",
          tabPanel("Сommon data",
            textOutput(outputId = "text1"),
            ),
          tabPanel("Results table",
                   dataTableOutput(outputId = "content")
            ),
          tabPanel("Graphic data")
        )
      )
    )

    # Define server logic required to draw a histogram
    server <- function(input, output) {

      fileinfor <- reactiveValues(file=NULL,
                                 ext=NULL,
                                 datapath=NULL)
      
      output$content <- renderDataTable({
        fileinfor$file <- input$fileInput
        fileinfor$datapath<-fileinfor$file$datapath
        fileinfor.datapath <- fileinfor$file$datapath
        fileinfor$ext <- tools::file_ext(fileinfor$datapath)
        req(fileinfor$file)
        validate(need(fileinfor$ext== "csv", "Please upload a csv file"))
        fread(fileinfor$datapath,
              showProgress = FALSE,
              sep=";", quote="",header=TRUE)
      })

      output$text1 <- renderUI(renderText({ 
        paste("Check ", fileinfor$datapath)
        }))
      
    }

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

在服务器端,我有几个问题:

  1. 如何正确获取数据,以便可以根据它创建变量并多次使用。在我的代码示例中,您可以看到下面的服务器端代码块不再看到创建的变量:

    输出 $ text1

  2. 您能否通过我的示例来说明操纵变量的创建及其应用?不知道去哪里以及如何移动?

【问题讨论】:

  • 您是计划让用户上传自己的数据,还是计划让用户只使用服务器上已有的数据?
  • @YBS 我们可以继续讨论吗?感谢您的帮助。

标签: r shiny data-science


【解决方案1】:

也许你正在寻找这个。

server <- function(input, output) {
  
  mydf <- reactive({
    req(input$fileInput)
    inData <- input$fileInput
    if (is.null(inData)){ return(NULL) }
    mydata <- read.csv(inData$datapath, header = TRUE, sep=",")
  })
  
  output$content <- renderDT(mydf())
  
  output$text1 <- renderText({
    req(input$fileInput)
    paste("Check ", input$fileInput$datapath)
  })
  
}

【讨论】:

  • 我不清楚你想用 text1 做什么。数据框中的所有变量都存在以供进一步使用。
  • 在您的示例中,您在 mydf 函数中创建了 mydata 变量。你从一个文件向它发送数据,就像在 P 中一样。现在,例如,我需要使用这些数据来进一步处理它并在其上构建一个图形。但是这个变量不再存在于函数之外。
  • 我也想用table fetch的结果来改变UI中创建的一些控件的参数,比如sliderInput。那就是我想在上传文件后计算年龄列中的最大值并重新配置这个控件。
  • 或许,我的回答here会对你有所帮助。
【解决方案2】:

首先,我要感谢@YBS 的教导。 多亏了这些提示,我设法解决了一半的问题。

解决方案的本质在于 Shainiy 如何处理变量。事实上,没有办法像编写常规代码那样存储变量。但是,您可以编写一个响应式函数,该函数将接收数据并在调用时将其发送到另一个函数框架内的变量。

需要注意的是,在教程“Mastering Shiny”中明确提到了这种方法

因此,获得了工作代码的一个版本。 如果你想尝试最终结果,那么依次销售以下步骤:

  1. 为我们的实验创建一个 CSV 文件:

    df

  2. 以“*csv”格式保存,使用命令:

    write.csv2(data_file,file = file.choose(new = T), row.names = FALSE, quote = FALSE)

  3. 使用下面提到的代码创建闪亮的应用程序:

            library("shiny")
            library("stringr")
            library("data.table")
            library("readr")
            library("DT")
            library("readr")
            library("here")
            library("ggplot2")
            library("dplyr")
            library("tidyr")
    
            # Define UI for application that draws a histogram
            ui <- fluidPage(
              titlePanel(h2(strong("Analysis of the composition and structure of residents"),
                         align = "center")),
              fileInput(
                inputId="fileInput",
                label="Choose file",
                multiple = FALSE,
                accept = ".csv",
                width = '100%',
                buttonLabel = "Choosing ...",
                placeholder = "No files selected yet"
              ),
              sidebarPanel(
                checkboxGroupInput(inputId="gender", label = "Choosing a gender feature:",
                  choices = c("Men" = "M",
                              "Women" = "F"),
                  selected= c("Men" = "M",
                              "Women" = "F")),
                sliderInput(inputId = "age", label = "Indicate the age group:",
                            min = 1, max = 100, value = c(1, 100)),
                selectInput(
                  inputId = "group",
                  label="Indicate the entrance",
                  choices=c(1:4),
                  selected = c(1:4),
                  multiple = TRUE,
                  selectize = TRUE,
                  width = NULL,
                  size = NULL
                )
              ),
              mainPanel(
                navbarPage("",
                  tabPanel("РЎommon data",
                    textOutput(outputId = "text1")
                    ),
                  tabPanel("Results table",
                    dataTableOutput(outputId = "content")
                    ),
                  tabPanel("Graphic data",
                    plotOutput(outputId = "my_plot")
                  )
                )
              )
            )
    
            # Define server logic required to draw a histogram
            server <- function(input, output) {
    
              fileinfor <- reactiveValues(file=NULL,
                                          ext=NULL,
                                          datapath=NULL)
    
    
              gender = reactive({
                gender <- input$gender
                gender
                })
              age = reactive({
                cbind(input$age[1],input$age[2])
                })
              group = reactive({
                input$group
                })
    
              import_data <- reactive({
                req(input$fileInput)
                fileinfor$file <- input$fileInput
                if (is.null(input$fileInput)){ return(NULL) }
                fileinfor$datapath<-fileinfor$file$datapath
                fileinfor$ext <- tools::file_ext(fileinfor$datapath)
                validate(need(fileinfor$ext== "csv", "Please upload a csv file"))
                import_data <- fread(fileinfor$datapath,
                      showProgress = FALSE,
                      sep=";", quote="",header=TRUE)
              })
    
    
              output$content <- renderDT({
                GENDER = gender()
                GROUP = group()
                AGE = age()
                req(import_data())
                data_file <- import_data()
                names(data_file) <- c("ID", "App", "Entrance", "Gender", "Age")
                data_file <- mutate_at(data_file, vars(Gender), as.factor)
                data_file<- mutate(data_file, Gender = factor(Gender, labels = c("F", "M")))
                data_file <- subset(data_file,data_file$Age>=AGE[1]
                                    & data_file$Age<=AGE[2]
                                    & data_file$Entrance %in% GROUP
                                    & data_file$Gender %in% GENDER)
                                         })
    
              output$text1 <- renderText({
                req(input$fileInput)
                gender <- gender()
                paste(length(gender))
              })
    
              output$my_plot= reactivePlot(function(){
                GENDER = gender()
                GROUP = group()
                AGE = age()
                req(import_data())
                data_file <- import_data()
                names(data_file) <- c("ID", "App", "Entrance", "Gender", "Age")
                data_file <- mutate_at(data_file, vars(Gender), as.factor)
                data_file<- mutate(data_file, Gender = factor(Gender, labels = c("F", "M")))
                data_file <- subset(data_file,data_file$Age>=AGE[1]
                                    & data_file$Age<=AGE[2]
                                    & data_file$Entrance %in% GROUP
                                    & data_file$Gender %in% GENDER)
    
                df <- group_by(data_file, data_file$Entrance, data_file$Gender)
                df <- summarise(df, N = n())
                names(df) <- c("Entrance", "Gender", "Quantity")
                df <- mutate_at(df, vars(Gender), as.factor)
                print(data_file$Gender)
                #df <- mutate(df, Gender = factor(Gender, levels  = c("f", "m")))
                df <- complete(df, Gender, fill = list(M = 0, F = 0))
    
                baseR.sbst.rssgn <- function(x) {
                  x[is.na(x)] <- 0
                  x
                }
    
                df$Quantity <- baseR.sbst.rssgn(df$Quantity)
    
                ggplot(data = df, aes(x = factor(df$Gender), y = df$Quantity, fill = df$Gender)) +
                  geom_bar(stat = "identity", position = position_dodge2(0.9)) +
                  geom_text(data = df, aes(label = df$Quantity, y = 0), vjust = -0.5, position = position_dodge2(0.9)) +
                  scale_fill_discrete(name = "Title", labels = c("F", "M")) +
                  facet_wrap(~ df$Entrance, nrow = 1, strip.position = "bottom") +
                  xlab("Distribution of residents by entrances, taking into account gender") +
                  ylab("Number of residents") +
                  theme(
                    strip.placement = "outside",
                    strip.background = element_blank(),
                    axis.text.x = element_blank(),
                    axis.ticks.x = element_blank()
                  )
    
    
                #?(ZMlength ~ Month, data = dat[dat$Lake == LAKE, ],
                #        main = "", xlab = "Month", ylab = "Shell length (mm)")
              })
    
    
            }
    
            # Run the application 
            shinyApp(ui = ui, server = server)
    

我没有解决什么问题:

  1. 我想在打开文件时立即计算“年龄”列中的最大值和最小值,并更改滑块输入的设置。我想对 selectInput 做同样的事情。
  2. 我想使用 Saini 应用程序不仅可以分析下载的数据,还可以补充 CSV 文件。在这部分,我什么都不知道。

【讨论】:

  • 请为每个问题分别发布MRE(最少可复制示例)。在这个过程中,您可能会自己解决问题。如果您确实在 SO 上发布您的问题,有人会帮助您。
猜你喜欢
  • 1970-01-01
  • 2018-05-17
  • 2022-12-17
  • 2017-02-11
  • 2018-04-08
  • 1970-01-01
  • 1970-01-01
  • 2016-07-06
  • 2014-04-11
相关资源
最近更新 更多