简体   繁体   English

表格为 output 基于 R shiny 中的用户输入

[英]Table as output based on user input in R shiny

I want to build an R Shiny app which creates a table showing input values from user and sums the up for the two numeric input variables.我想构建一个 R Shiny 应用程序,该应用程序创建一个表格,显示来自用户的输入值并将两个数字输入变量的总和相加。

I have defined the following input我已经定义了以下输入

# Define UI for application that returns table based on input values
ui <- fluidPage(

    # Application title
    titlePanel("Jack & Jones battle over the Castle!"),

    # Input
    dateInput('date', "Choose today's date:", value = NULL, min = NULL, max = NULL,
              format = "yyyy-mm-dd", startview = "month", weekstart = 0,
              language = "en", width = NULL),
    numericInput("Score Jack", label = "Submit Score Jack", value = 0, min = 0, max = 300, step = 1, width = '10%'),
    numericInput("Score Jones", label = "Submit Score Jones", value = 0, min = 0, max = 300, step = 1, width = '10%'),
    submitButton("Submit Scores", icon("Submit") , width = NULL)
)

As an output I would like to return a table with a new row for each of the inputs eg three columns (date, score Jack, score Jones) and a row at the end of the table to sum the two score columns when the 'Submit' button is used.作为 output,我想返回一个表,其中每个输入都有一个新行,例如三列(日期、得分 Jack、得分 Jones)和表格末尾的一行,以在“提交”时对两个得分列求和' 按钮被使用。 I've tried to work with the renderTable function, but so far yielded no results.我尝试使用 renderTable function,但到目前为止没有产生任何结果。 When searching for similar questions, I found work arounds using the DT package.在搜索类似问题时,我找到了使用 DT package 的解决方法。 However, it does no seem to exist anymore.然而,它似乎已经不存在了。

I'm new to Shiny so would appreciate any input.我是 Shiny 的新手,所以会很感激任何输入。

Find below a small working example.在下面找到一个小的工作示例。 The data frame you want to render is stored in a reactiveValues (as per Add values to a reactive table in shiny ).您要呈现的数据帧存储在reactiveValues中(根据Add values to a reactive table in shiny )。 A row is added once the button (which I turned into an actionButton and named "submitButton") is clicked, via the observeEvent(...) line.一旦通过observeEvent(...)行单击按钮(我变成了一个actionButton并命名为“submitButton”),就会添加一行。

library(shiny)

# Define UI for application that returns table based on input values
ui <- fluidPage(

    # Application title
    titlePanel("Jack & Jones battle over the Castle!"),

    # Input
    dateInput('date', "Choose today's date:", value = NULL, min = NULL, max = NULL,
              format = "yyyy-mm-dd", startview = "month", weekstart = 0,
              language = "en", width = NULL),
    numericInput("scoreJack", label = "Submit Score Jack", value = 0, min = 0, max = 300, step = 1, width = '10%'),
    numericInput("scoreJones", label = "Submit Score Jones", value = 0, min = 0, max = 300, step = 1, width = '10%'),
    actionButton("submitButton", "Submit Scores", icon("Submit") , width = NULL),

    # Output
    tableOutput("table")
)

# Define server logic required to render the table
server <- function(input, output) {
    values <- reactiveValues()
    values$df <- data.frame(data = character(), jack = character(), jones = character())

    observeEvent(input$submitButton, {
        new_row <- data.frame(data = strftime(input$date, "%Y-%m-%d"), jack = input$scoreJack, jones = input$scoreJones)
        values$df <- rbind(values$df, new_row)
    })

    output$table <- renderTable(values$df)
}

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

This app adds a total score column, it also automatically sorts the data by date, just in case a user does not add dates chronologically.这个应用程序添加了一个总分列,它还会自动按日期对数据进行排序,以防万一用户没有按时间顺序添加日期。

With regards to my comment about the Total Score row, I've set the row name of the total score row to "Total Score", which will put Total Score in the final row rather than the row number like for the rest of the rows.关于我对总分行的评论,我将总分行的行名设置为“总分”,这会将总分放在最后一行,而不是像 rest 那样的行号. The total score shows the date of the most recent date in the data frame rather than the date of the last user input.总分显示数据框中最近日期的日期,而不是最后一次用户输入的日期。

library(shiny)

ui <- fluidPage(

  # Application title
  titlePanel("Jack & Jones battle over the Castle!"),

  # Input
  dateInput('date', "Choose today's date:", value = NULL, min = NULL, max = NULL,
            format = "yyyy-mm-dd", startview = "month", weekstart = 0,
            language = "en", width = NULL),
  numericInput("Score Jack", label = "Submit Score Jack", value = 0, min = 0, max = 300, step = 1, width = '10%'),
  numericInput("Score Jones", label = "Submit Score Jones", value = 0, min = 0, max = 300, step = 1, width = '10%'),
  actionButton("submit", "Submit Scores", icon("Submit") , width = NULL, style="color: #fff; background-color: #337ab7; border-color: #2e6da4"), 
  DT::DTOutput("score_table")
)

table_data <- data.frame(Date = as.Date(as.character()), `Score Jack` = as.numeric(), `Score Jones` = as.numeric(), check.names = FALSE)

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

  tableValues <- reactiveValues(df = data.frame(Date = as.Date(as.character()), `Score Jack` = as.numeric(), `Score Jones` = as.numeric(), check.names = FALSE))


  observeEvent(input$submit, {

    temp <- tableValues$m

    newRow <- data.frame(Date = input$date, `Score Jack` = input$`Score Jack`, `Score Jones` = input$`Score Jones`, check.names = FALSE)


    if(!is.null(temp)) {

      if(isolate(input$date) < temp[nrow(temp), 1]) {
        temp <- rbind(temp, newRow)
        temp <- dplyr::arrange(temp, Date)
      } else {
        temp <- rbind(temp, newRow)
      }
    } else {
      temp <- rbind(temp, newRow)
    }

    tableValues$m <- temp

  })


  output$score_table <- DT::renderDataTable({

    if(!is.null(tableValues$m)){

      table_data <- tableValues$m

      totalScore <- data.frame(Date = table_data[nrow(table_data),1], `Score Jack` =  sum(table_data$`Score Jack`), `Score Jones` = sum(table_data$`Score Jones`), check.names = FALSE)

      table_data <- rbind(table_data, totalScore)

      if(nrow(table_data > 2)){
        table_data <- dplyr::arrange(table_data, Date)
      }
    }
    rownames(table_data)[nrow(table_data)] <- "Score Total"
    table_data

  })

  observe({print(colnames(tableValues$m))})
  observe({print(!is.null(tableValues$m))})

}

shinyApp(ui, server)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM