0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

R/Shiny でテーブルから選択、制御する方法

Posted at

はじめに

R/Shiny でインタラクティブにテーブルを操作したいという要求があった。例えばテーブルの選択したデータをプロット上で強調させたり、その数値を表示させたりしたい場合がある。これを可能にするのがDTパッケージと、_rows_selectedコマンドである。

また本記事で使用したデータセットは「Rでの性別、身長、体重、血液型データの作成方法」で作成したものを「R shiny でデータの基礎分析用アプリの作成①」で csv に保存したので、それを用いて行った。

テーブルから選択した行の情報を表示する Shiny アプリケーション

DTパッケージの選択の制御を行うのは、DT::renderDataTableselectionオプションで制御する。selection=list()の中身で、modeで単数選択か複数選択かを選び、targetで選択する対象(行、列、セル)を決め、selectedで初期に選択済みの行(列、セル)を指定する。例えばtargetを行(row)にした場合、選択したテーブルのidを用いて、サーバー側でinput${id}_row_selectedで、何行目を選択しているかの情報を得ることができる。

以下、Rのサンプルコードを示す。

library(shiny)
library(DT)

df <- read.csv("data.csv")

ui <- fluidPage(
  titlePanel("DT test"),
  mainPanel(
    dataTableOutput("data"),
    br(),
    h4("選択した行:"),
    verbatimTextOutput("row"),
    h4("選択した性別:"),
    verbatimTextOutput("sex"),
    h4("選択した身長:"),
    verbatimTextOutput("height"),
    h4("選択した体重:"),
    verbatimTextOutput("weight")
  )
)

server <- function(input, output) {
  output$data <- DT::renderDataTable({
    df
  }, 
  extensions = c('Buttons'), 
  selection = list(mode = 'single', selected = c(1), target ='row'),
  options = list(dom = 'Blfrtip', buttons = c('csv', 'excel', 'pdf'), lengthMenu = c(5, 10, 20), pageLength = 5)
  )
  
  output$row <- renderText({ input$data_rows_selected })
  output$sex <- renderText({ df$SEX[input$data_rows_selected] })
  output$height <- renderText({ df$HEIGHT[input$data_rows_selected] })
  output$weight <- renderText({ df$WEIGHT[input$data_rows_selected] })
}

shinyApp(ui = ui, server = server)

アプリ画面は以下の様になる。

DT_selected.png

3行目が選択されていて、下部にそのデータフレームの中身が表示されているのが分かる。

おわりに

これを応用して、プロットなどと組み合わせれば、選択した行のデータのみマークを変更するようなアプリケーションも実装可能である。DTパッケージはインタラクティブに使えるオプションが多数あるので、それも記事にしていけたらと思う。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?