0

如果您运行下面的 R 闪亮脚本,我们会在仪表板中看到两个框,左侧框有条形图,右侧有 DT 表,当我使用 event_data("plotly_click") 单击图表的任何条形时,我想要对应的Employee要显示在表中,如单击第一个栏时,“r1”应显示在表中。我尝试做“user_cases$base1[d[3]]”,但它抛出一个错误为“错误:无效的下标类型'list'”。我将附上快照以供参考,请帮助我。

## app.R ##
library(shiny)
library(shinydashboard)
library(ggplot2)
library(plotly)
library(DT)
ui <- dashboardPage(
dashboardHeader(title = "Sankey Chart"),
dashboardSidebar(
width = 0
),
dashboardBody(
box(title = "Sankey Chart", status = "primary",height = "455" ,solidHeader = 
T,
plotlyOutput("sankey_plot")),

box( title = "Case Summary", status = "primary", height = "455",solidHeader 
= T, 
     dataTableOutput("sankey_table"))
)
)
server <- function(input, output) 
{ 

output$sankey_plot <- renderPlotly({
height2 = c(56,45,23,19,8)
base1 = c("r1","r4","r2","r5","r3")
user_cases = data.frame(base1,height2)
pp1 <<- ggplot(user_cases, aes(x = reorder(base1,-height2), y = height2)) + 
  geom_bar(stat = "identity", fill = "#3399ff" ) + scale_y_discrete(name 
="Cases") + scale_x_discrete(name = "Employee")
ggplotly(pp1, tooltip="text",height = 392)
})
output$sankey_table <- renderDataTable({
d <- event_data("plotly_click")
user_cases$base1[d[3]]
})
}
shinyApp(ui, server)

带条形图的 DT 表

要获取的数据集

我正在尝试从 bupaR 库的患者数据集中获取数据子集。执行此操作的代码如下:

patients_final <- patients[patients$employee == as.data.frame( 
user_time$employee[as.numeric(d[3])])]

但我得到的错误是:“不能使用矩阵或数组进行列索引”附加快照以获得帮助。

条形图的快照

4

1 回答 1

1

看看修改后的代码,我改成user_cases$base1[d[3]]as.data.frame(user_cases$base1[as.numeric(d[3])])

 ## app.R ##
  library(shiny)
  library(shinydashboard)
  library(ggplot2)
  library(plotly)
  library(DT)


  height2 = c(56,45,23,19,8)
  base1 = c("r1","r4","r2","r5","r3")
  user_cases = data.frame(base1,height2)


  ui <- dashboardPage(
    dashboardHeader(title = "Sankey Chart"),
    dashboardSidebar(
      width = 0
    ),
    dashboardBody(
      box(title = "Sankey Chart", status = "primary",height = "455" ,solidHeader = 
            T,
          plotlyOutput("sankey_plot")),

      box( title = "Case Summary", status = "primary", height = "455",solidHeader 
           = T, 
           dataTableOutput("sankey_table"))
    )
  )


  server <- function(input, output) 
  { 

    output$sankey_plot <- renderPlotly({

      pp1 <<- ggplot(user_cases, aes(x = reorder(base1,-height2), y = height2)) + 
        geom_bar(stat = "identity", fill = "#3399ff" ) + scale_y_discrete(name 
                                                                          ="Cases") + scale_x_discrete(name = "Employee")
      ggplotly(pp1, tooltip="text",height = 392)
    })
    output$sankey_table <- renderDataTable({
      d <- event_data("plotly_click")
     as.data.frame( user_cases$base1[as.numeric(d[3])])
    })
  }
  shinyApp(ui, server)

输出如下:

在此处输入图像描述

您可以根据需要修改dataframe输出。

希望能帮助到你!

于 2017-12-12T11:53:42.323 回答