如何从自定义函数中获取汇总表以对用户输入的变量作出反应?

问题描述 投票:0回答:1

这是我第一次尝试使用Shiny。

我有一个具有4个变量的模拟患者水平数据集:

  • group:分类,取值A,B和C。代表研究中使用的3种不同的治疗类型。
  • week:数字变量,取值1、4、8,表示随访周。
  • painscore:数字变量,得分为1-10,其中1表示没有痛苦,10表示极端痛苦。
  • dependscore:数字变量,得分为1-10,其中1表示对疼痛药物没有依赖性,10表示极端依赖性。

[试图构建一个简单的应用程序,它接受两个输入:星期和变量,并提供两个输出:

  1. 所选星期内所选变量得分分布的箱线图。 x轴代表组的3个级别(A,B和C)。
  2. 汇总表显示了观察次数,中位数,第25个百分点,第75个百分点和缺失数。

我能够创建交互式箱线图,但我无法创建摘要表。我可以使用doBy中的summaryBy函数在RMarkdown中创建此表的静态版本,但无法在Shiny中实现它。尝试遵循建议herehere,但我缺少一些内容。

这是我的可重复性代码。打扰一下,广泛的注释(我是一个完整的初学者)对我自己比对其他人更重要。



#libraries--------------------

library(shiny)
library(tidyverse)
library(knitr)
library(doBy)


#----------------------------

#input data
set.seed(123)
mydf <- data.frame( group     =   rep(rep(c("A","B","C"), each = 3), times = 3),
                    week      =   rep(rep(c(1,4,8), each = 9)),
                    painscore =   sample(1:10, 27, replace = TRUE),
                    dependscore = sample(1:10, 27, replace = TRUE) )

#--------------------------

#define custom function to calculate summary statistics for column of interest. 
#function explained in a little more detail when applied in the server function.

fun <- function(x) { 
    c( n = length(x),
       m = median(x), 
       firstq = round(quantile(x)[2], 1), 
       lastq = round(quantile(x)[4], 1), 
       missing = mean(is.na(x)))
}

#-------------------------


#UI
ui <- fluidPage(

     titlePanel("Shiny Boxplot and Table"),

    #User can provide two different inputs
    sidebarLayout(
        sidebarPanel(
            #1. allow user to pick week using radiobuttons
            radioButtons(inputId = "pickedwk",
                        label = "week you want to display",
                        choices = c(1,4,8),
                        selected = 1), 
            #2. user can pick variable to visualize using dropdownboxes
            selectInput(inputId = "var",
                        label = "variable to visualize",
                        list("How much pain did you feel today?" = "painscore",
                             "How dependent are you on medication?" = "dependscore")), 
            #helpertext
            helpText("Enter week/variable choices here") 
                     ),

     #Spaceholders for output
         mainPanel(
                     plotOutput("boxplot"), #boxplot placeholder
                     htmlOutput("descriptives") #kable html table placeholder
                  )
                )
             )
#-------------------------
#Server
server <- function(input, output) {




    #create dataset that subsets down to the week picked by user.
    weeksub <- reactive({
        mydf %>% filter(week == input$pickedwk[1])
                        }) 
    #1. use reactive datasubset to render boxplot.
    output$boxplot <- renderPlot({ 
        ggplot(weeksub(), aes_string(x = "group", y = input$var)) + #input$var works here
        geom_boxplot(fill = "red", outlier.shape = 15, outlier.color = "black") +
        scale_y_continuous(name = as.character(input$var)) +
        scale_x_discrete(name = "group") +
        ggtitle(paste("Distribution of", as.character(input$var), "by treatment group"))  
    })



    #2. use same reactive datasubset to render kable descriptive statistics for the variable picked.

    output$descriptives <- renderText({

        kable(summaryBy(input$var ~ group, data = as.data.frame(weeksub()), FUN = fun),
      #note: here, I'm using the summaryBy function from package doBy. It takes the form var~ categoricalvar
      # so, either painscore ~ group, or dependscore ~ group depending on what the user picked, and uses
      #my custom function to return a table of count, median, 25th percentile, 75th percentile and missing count for 
      #the 3 levels of the group variable (for A, B, and C)
        col.names = c("Number", "Median", "1Q", "3Q", "Missing"))

    })



}#server function ends


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


r shiny shiny-reactivity
1个回答
0
投票

您的代码中有两个问题:

  • 公式符号不知道如何处理input$varsummaryBy支持更好的替代语法。 (您也可以使用as.formulapaste建立公式。)
  • 您缺少col.names中的“组”列
  • 您必须从kable生成HTML并将其作为HTML传递到UI。

将表输出更改为此:

  output$descriptives <- renderUI({
    HTML(kable(summaryBy(list(input$var, 'group'), data = as.data.frame(weeksub()), FUN = fun),
          col.names = c('Group', "Number", "Median", "1Q", "3Q", "Missing"),
          format='html'
          ))
  })
© www.soinside.com 2019 - 2024. All rights reserved.