2017-08-07 18 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

相關問題