【问题标题】:How to use loop to generate the data in a table in Shiny?如何使用循环在 Shiny 的表中生成数据?
【发布时间】:2021-10-25 17:53:06
【问题描述】:

刚开始学习shiny几天,被这个问题困扰了很久。

我需要生成一个表格(双列表),表格中的数据需要根据输入进行计算(然后我可以使用这个表格在ggplot()中生成散点图)。

我试图让代码更可见,所以我想使用 for 循环来替换可能数百行高度重复的代码。否则,它将看起来像(input$meansy1)-1)^2(input$meansy1)-2)^2......(input$meansy1)-100)^2

不知道为什么在data.frame()中不能正确使用。 这是部分代码,

shinyUI(fluidPage(

numericInput("y1", "y1:", sample(1:100,1), min = 1, max = 100)),
tableOutput("tb")
))
shinyServer(function(input, output,session) {
      
    list <-c()
    for (i in 1:100) {
      local({
        list[[i]] <-reactive(((input$y1)-i)^2)}
        )}
  
  dt = data.frame(y_roof = 1:100, B=list)

  output$tb <- renderTable({ 
    dt
     })

})

【问题讨论】:

    标签: r shiny shiny-server shinyapps


    【解决方案1】:

    在为闪亮的应用程序开发功能时,将底层操作与闪亮的上下文分开查看是有意义的。这样你就可以判断你是否有一个闪亮的特定问题。

    让我们先看一下您要执行的操作:迭代地从 x 中减去 1 到 100 的值,然后对结果进行平方。

    您可以在基础 R 中执行此操作,如下所示:

    x <- 1
    dt1 <- data.frame(y_roof = 1:100)
    (x - dt1$y_roof)^2
    #>   [1]    0    1    4    9   16   25   36   49   64   81  100  121  144  169  196
    #>  [16]  225  256  289  324  361  400  441  484  529  576  625  676  729  784  841
    #>  [31]  900  961 1024 1089 1156 1225 1296 1369 1444 1521 1600 1681 1764 1849 1936
    #>  [46] 2025 2116 2209 2304 2401 2500 2601 2704 2809 2916 3025 3136 3249 3364 3481
    #>  [61] 3600 3721 3844 3969 4096 4225 4356 4489 4624 4761 4900 5041 5184 5329 5476
    #>  [76] 5625 5776 5929 6084 6241 6400 6561 6724 6889 7056 7225 7396 7569 7744 7921
    #>  [91] 8100 8281 8464 8649 8836 9025 9216 9409 9604 9801
    

    要将结果存储在数据框中,请将最后一行更改为:

    dt1$col2 <- (x - dt1$y_roof)^2
    
    head(dt1)
    #>   y_roof col2
    #> 1      1    0
    #> 2      2    1
    #> 3      3    4
    #> 4      4    9
    #> 5      5   16
    #> 6      6   25
    

    在 tidyverse 中执行相同的操作如下所示:

    library(dplyr)
    
    dt2 <- 
      data.frame(y_roof = 1:100) %>% 
      mutate(col2 = (x - y_roof)^2)
    
    head(dt2)
    #>   y_roof col2
    #> 1      1    0
    #> 2      2    1
    #> 3      3    4
    #> 4      4    9
    #> 5      5   16
    #> 6      6   25
    

    现在我们可以在闪亮的应用程序中使用它:

    library(shiny)
    library(dplyr)
    ui <-
      shinyUI(fluidPage(
        numericInput("y1", "y1:", sample(1:100, 1), min = 1, max = 100),
        tableOutput("tb")
      ))
    
    server <-
      shinyServer(function(input, output, session) {
        
        output$tb <- renderTable({
          data.frame(y_roof = 1:100) %>%
            mutate(col2 = (input$y1 - y_roof) ^ 2)
        })
        
      })
    shinyApp(ui, server, options = list(launch.browser = TRUE))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 2021-01-11
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多