在Shiny响应式结构中对数据框进行子集筛选

4

我无法在反应式闪亮结构中对数据框进行子集并将其显示为表格。如果我尝试仅显示数据框,则可以,但无法对其进行子集和显示。我相信这与使用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))

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")))))

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()})

 })
1个回答

5
这是因为您只选择了b数据框的一列。这种子集的结果是一个向量,而不是数据框,因此renderDataTable无法呈现它。
您可以在反应表达式中将向量转换为数据框:
  datum<-reactive({
    d <- b[,input$col]
    d <- as.data.frame(d)
    colnames(d) <- input$col
    d
  })

一种更简单的解决方案是使用 @docendo discimus 的评论:
datum<-reactive({ d<-b[,input$col,drop=FALSE] 
d })

3
或者 b[ , input$col, drop = FALSE] - talat
我只是在寻找以下代码:datum<-reactive({ d<-b[,input$col,drop=FALSE] d<-as.data.frame(d) }) 谢谢,它起作用了。 - Shoaibkhanz
@docendodiscimus,您的评论帮助我获取了headers - Shoaibkhanz
@Shoaibkhanz,你只需要使用datum<-reactive({ b[, input$col, drop = FALSE]}) - talat
@docendodiscimus,是的,它做到了。 - Shoaibkhanz
@docendodiscimus 和 Nice-- 请你们也看一下这个问题,http://stackoverflow.com/questions/29251438/unable-to-use-reactive-element-in-my-shiny-app - Shoaibkhanz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接