2017-08-07 16 views
2

小问题在这里:我知道我可以通过input$dfname_rows_selected访问选定的行,它回送选择的行数,但是如何读取行名称而不是数字?在我的情况下,它们不是按照我以后使用它们的顺序生成的,因此我需要获取里面的值才能使其正常工作。获取选定的行值而不是闪亮的数字使用DT

编辑:添加例子

ui <- shinyUI(fluidPage(

    DT::dataTableOutput("table"), 
    actionButton("btn", "press me") 

)) 

server <- function(input, output) { 
    observeEvent(input$btn, { 
    print(input$table_rows_selected) 
    }) 

    output$table <- DT::renderDataTable({ 

    mtcars %>% 
     datatable(selection = "multiple") 

    }) 

} 
shinyApp(ui = ui, server = server) 
+0

请出示一个小重复的例子,并且预期输出 – akrun

+1

好吧,我会在某一时刻 –

回答

2

事情是这样的:

library(shiny) 
library(DT) 

ui <- basicPage(
    mainPanel(DT::dataTableOutput('mytable')), 
    textOutput("selected") 
) 

server <- function(input, output,session) { 

    mydata <- reactive({mtcars}) 

    output$mytable = DT::renderDataTable( 
    datatable(mydata()) 
) 

    selectedRow <- eventReactive(input$mytable_rows_selected,{ 
    row.names(mtcars)[c(input$mytable_rows_selected)] 
    }) 

    output$selected <- renderText({ 
    selectedRow() 
    }) 
} 
runApp(list(ui = ui, server = server)) 
1

我不认为你可以。你可以做的是在创建数据表之前编写一个被动的,在其中对数据框进行所有修改。一个例子:

library(shiny) 
library(DT) 

ui <- shinyUI(fluidPage(
    DT::dataTableOutput("table"), 
    textOutput("selectedcar") 
) 
) 

server <- function(input, output,session) { 

    # the reactive where we filter/sort/modify the data 
    reactive_df <- reactive({ 
    mtcars[order(mtcars$cyl),] 
    }) 

    # This datatable uses the reactive directly, so no more modifications 
    output$table <- DT::renderDataTable({ 
    DT::datatable(reactive_df()) 
    }) 

    # now we can get the row/rowname as follows: 
    output$selectedcar <- renderText({ 
    paste0(rownames(reactive_df())[input$table_rows_selected], collapse = ", ") 
    }) 
} 


shinyApp(ui, server) 

希望这有助于!

+0

真奇怪。这对我来说可以? – Florian

+0

我认为命名是错误的,现在它的工作:) –

+0

很好,我在dataTableOutput之前添加了DT ::以确保它不使用闪亮版本,这可能是问题所在。 – Florian

相关问题