【问题标题】:How to assign row names to a reactive data frame in Shiny?如何将行名称分配给 Shiny 中的反应性数据框?
【发布时间】:2021-03-28 14:21:03
【问题描述】:

我正在尝试做一些在 R 脚本中很容易实现的事情,但是当成为 Shiny 应用程序的一部分时,我正在努力复制。我正在使用“reactive({})”读取文件(下面提供的测试代码中的这部分已替换为测试数据集,第 13-16 行)。我想获取变量“物种”条目并将它们分配给数据框行名。我尝试了两种方法

  1. 在“reactive({})”语句中,第 13-16 行

  2. 通过创建一个新的数据框 df1,第 18-20 行

但由于某种原因,这两种方法都行不通。

非常感谢您!

library(shiny)
library(DT)
library(datasets)

ui <-  basicPage("",
  DT::dataTableOutput("table"),
  verbatimTextOutput("head1"),
  verbatimTextOutput("head2")
)

server <-  function(input, output, session) {
  
  df <- reactive({
    df <- data.frame(v1=c("a", "b"), v2=c(10,20))
#    row.names(df) <- df[,1]           # THIS DOES NOT WORK
  })
  
  df1 <- reactive({                    # THIS ALSO DOESN'T WORK
    row.names(df()) <- df()[,1]
  })

  # Show data in a table ----
  output$table <- DT::renderDataTable({
    datatable(
      {df()}, 
      filter = 'top', 
      class="cell-border stripe", 
      rownames = TRUE
    ) # end of datatable
  })
  
  output$head1 <- renderPrint({
    head(df())
  })
  
  output$head2 <- renderPrint({
    head(df1())
  })
  
}

shinyApp(ui = ui, server = server)

【问题讨论】:

  • 你确定它在 R 中工作没有闪亮吗?我收到不允许双行名称(非唯一)的错误,请尝试例如与testdf &lt;- iris; row.names(testdf) &lt;- testdf$Species
  • @starja - 嗯,你是对的,一定与数据集有关,因为这个工作:``` r df v1 v2 #> 1 a 10 #> 2 b 20 df v1 v2 #> aa 10 #> bb 20 ``` reprex package (v0.2.1) 于 2020-12-17 创建跨度>
  • @starja - 我将原始问题中的数据框更改为在使用 R 脚本时可以正常工作但作为 Shiny 实现失败的数据框。不知道为什么 iris 数据集表现不同。

标签: r shiny


【解决方案1】:

试试这个

library(shiny)
library(DT)
library(datasets)

ui <-  basicPage("",
                 DTOutput("table"),
                 DTOutput("head1"),
                 DTOutput("head2")
)

server <-  function(input, output, session) {
  
  df <- reactive({
    df <- data.frame(v1=c("a", "b"), v2=c(10,20))
    row.names(df) <- df[,1]           # THIS WORKs
    df
  })
  
  df1 <- reactive({                    # THIS ALSO WORKs
    data <- df()
    row.names(data) <- df()[,1]
    data
  })
  
  # Show data in a table ----
  output$table <- renderDT({
    datatable(
      {df()}, 
      filter = 'top', 
      class="cell-border stripe", 
      rownames = TRUE
    ) # end of datatable
  })
  
  output$head1 <- renderDT({
    head(df())
  })
  
  output$head2 <- renderDT({
    head(df1())
  })
  
}

shinyApp(ui = ui, server = server)

【讨论】:

  • 为什么起作用:reactives 就像函数,所以 reactive 的值是函数中的返回值/最后一个值。如果 rowname 设置是函数中的最后一个值,则会导致问题,因此您必须最后返回实际的 data.frame
猜你喜欢
  • 2018-10-16
  • 2021-01-14
  • 2021-03-12
  • 1970-01-01
  • 2018-10-21
  • 1970-01-01
  • 2019-01-15
  • 2016-04-10
  • 2014-11-03
相关资源
最近更新 更多