无法使用Shiny中的radioButtons显示多列

时间:2018-11-27 11:08:11

标签: r input datatable shiny dt

希望大家一切都好。我在服务器的反应部分中遇到问题(如果为else语句)。 使用 radioButtons 选择 TTS NTTS 后,我分别需要mtcars数据的1:6和7:11列。我已附上与所需输出匹配的图片。 我还附上了我的密码,有人可以找出它们的问题吗? 非常感谢:)

when 'NTTS' selected

when 'TTS' selected

when 'All' is selected

library(shiny)
library(tidyr)
library(dplyr)
library(readr)
library(DT) 

data_table <- mtcars

# Define UI
ui <- fluidPage(
downloadButton('downLoadFilter',"Download the filtered data"),

radioButtons(inputId = "columns", label = "choose variable",
    choices =c("All","TTS", "NTTS"),
    selected = c("All")),

selectInput(inputId = "cyl",
    label = "cyl:",
    choices = c("All",
                unique(as.character(data_table$cyl))),
    selected = "4",
    multiple = TRUE),

selectInput(inputId = "vs",
    label = "vs:",
    choices = c("All",
                unique(as.character(data_table$vs))),
    selected = "1",
    multiple = TRUE),

DT::dataTableOutput('ex1'))

server <- function(input, output) {

thedata <- reactive({

if(input$columns=='All'){
data_table
}

else if  (input$columns== 'TTS'){
data_table<-  data_table[,c(1:6),drop=FALSE]    }

else   
data_table<-  data_table[,c(7:11),drop=FALSE]

if(input$cyl != 'All'){
data_table<-data_table[data_table$cyl %in%   input$cyl,]
}

if(input$vs != 'All'){
data_table<-data_table[data_table$vs %in%  input$vs,]
}

else
data_table })

output$ex1 <- DT::renderDataTable(DT::datatable(filter = 'top',
                                        escape = FALSE, 
                                        options = list(pageLength = 
                                                         10, 
scrollX='500px',autoWidth = TRUE),{
                                                 thedata() # Call reactive 

}))

output$downLoadFilter <- downloadHandler(
filename = function() {
paste('Filtered data-', Sys.Date(), '.csv', sep = '')
},
content = function(path){
write_csv(thedata(),path) # Call reactive thedata() 
})}

shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:1)

问题与Shiny或Datatable无关,它来自我们对数据进行子集和覆盖的方式。
如果我们首先对列进行子集并覆盖sayHello,则<Button/>data_table中的一个不再存在,并且基于丢失的列过滤行会导致vs,所有行迷路了。

简单修复:重新排列子设置,先按行过滤,然后按列过滤:

cyl