繁体   English   中英

如何将行名称分配给 Shiny 中的反应数据框?

[英]How to assign row names to a reactive data frame in Shiny?

我正在尝试做一些在 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)

尝试这个

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)

暂无
暂无

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

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