在闪亮的反应结构中子集数据帧

Sho*_*anz 3 r shiny

我无法在反应性闪亮结构中对数据帧进行子集化并将其显示为表格.如果我尝试只显示数据帧,我能够但无法进行子集和显示.我相信它必须采用这种方式input$.

请帮助,我很有光泽

数据集

dput(b)
structure(list(Date = c("1-Jan", "2-Jan", "3-Jan"), Month = c("Jan", 
"Jan", "Jan"), Days = c("Thu", "Fri", "Sat"), A = c(30712L, 26842L, 
21640L), B = c(26505L, 25906L, 22929L), C = c(22128L, 26814L, 
22091L), D = c(30994L, 23935L, 20048L), E = c("38%", "51%", "37%"
), F = c(71L, 70L, 71L), G = c(91L, 114L, 104L), H = c(77L, 98L, 
91L), I = c(-4621L, -463L, 291L), J = c("-32.00%", "-3.30%", 
"2.00%")), .Names = c("Date", "Month", "Days", "A", "B", "C", 
"D", "E", "F", "G", "H", "I", "J"), class = "data.frame", row.names = c(NA, 
-3L))
Run Code Online (Sandbox Code Playgroud)

ui.R

library(shiny)
library(shinythemes)

shinyUI(fluidPage(                  
  sidebarLayout(   
    sidebarPanel(
      selectInput(inputId = "col", label = "Columns",choices = colnames(b[4:8]),selected = colnames(b[4]))),

    mainPanel(dataTableOutput(outputId = "table")))))
Run Code Online (Sandbox Code Playgroud)

server.R

library(shiny)
library(shinythemes)
library(ggplot2)
library(dplyr)

b<-read.csv("newb.csv",header=TRUE,sep=",",stringsAsFactors=FALSE)

shinyServer(function(input, output) {

  datum<-reactive({
    d<-b[,input$col]
    return(d)
  })

  output$table<-renderDataTable({datum()})

 })
Run Code Online (Sandbox Code Playgroud)

Nic*_*icE 5

发生这种情况是因为您只选择b数据框的一列.此子集的结果是向量,而不是数据帧,因此renderDataTable无法呈现它.

您可以将矢量转换为反应式表达式中的数据框:

  datum<-reactive({
    d <- b[,input$col]
    d <- as.data.frame(d)
    colnames(d) <- input$col
    d
  })
Run Code Online (Sandbox Code Playgroud)

使用@docendo discimus的评论更简单的解决方案:

datum<-reactive({ d<-b[,input$col,drop=FALSE] 
d })
Run Code Online (Sandbox Code Playgroud)

  • 或者`b [,输入$ col,drop = FALSE]`也许? (3认同)