[英]Using reactive calls in a tabPanel environment in Shiny
我正在努力在Shiny的tabPanel環境中使用反應性環境。
我想在Shiny的inputPanel中的tabPanel環境中使用反應數據文件。 下面是代碼(我在下面生成要在C:/ Temp中使用的數據):
數據:
dir.create(file.path("C:","Temp"), showWarnings = FALSE)
write.csv(rbind("A","B","C","D"), "C:/Temp/A.csv",row.names = FALSE)
write.csv(rbind("A","B","C","D"), "C:/Temp/B.csv",row.names = FALSE)
write.csv(rbind("A","B","C","D"), "C:/Temp/C.csv",row.names = FALSE)
閃亮:
---
title: "Reactive in Tab environment"
output: html_document
runtime: shiny
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r , echo=FALSE}
navbarPage("Analysis",
tabPanel("File Choice",
inputPanel(
selectInput("File", label = "File Choice",
choices = c("A","B","C"), selected = c("A","B","C")[1])
),
Data <- reactive({read.csv(paste0("C:/Temp/",input$File,".csv"))})
),
tabPanel("File Show",
inputPanel(
selectInput("Choices", label = "Choices",
choices = Data()[,1], selected = Data()[,1][1])
)))
```
我認為在RMarkdown文檔中編寫閃亮的應用程序可能會有些混亂,因為UI /服務器輸入/輸出之間的區別沒有明確定義。
我將采用您的反應性值( Data
)和服務器中要使用的其他內容,並在UI組件(navbarPage,tabPanels等)之外定義它們。
我還喜歡分別編寫各種接口組件,但這只是個人喜好(您也可以將它們寫在不同的文檔中並提供它們以縮小代碼范圍)。
在下面的示例(與您的示例非常相似)中,可以在一個選項卡中選擇三個文檔,然后在另一個選項卡下將其打印為表格。 請注意,您將需要修復路徑以轉到擁有文檔的位置(我將使用file.path
因此您知道在不同的操作系統上不會有問題)。
---
title: "Reactive in Tab environment"
runtime: shiny
output:
html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
## For reproducibility you can run this to create a Temp directory with
## some data.frames in your current directory
if (!file.exists('Temp')) {
dir.create('Temp')
for (f in paste0(LETTERS[1:3], '.csv'))
write.csv(data.frame(A=sample(letters[1:10]), B=sample(10)), file.path('Temp', f))
}
```
```{r app, echo=FALSE}
## Initialize data with something
## Replace the path in `file.path` with the path to your files
docs <- paste0(LETTERS[1:3], '.csv') # your documents
Data <- reactive({
f <- if (is.null(input$File)) docs[[1]] else input$File # initialize reading A.csv
read.csv(file.path('Temp', f))
})
## UI components
## Note: these are not reactive, so when you want to use a reactive value like Data(),
## wrap it in isolate().
## I like to separate things, but also could plug in to tabPanels
panel1 <- tagList(
inputPanel(
selectInput("File", label = "File Choice",
choices = docs, selected=docs[[1]])
)
)
panel2 <- tagList(
sidebarLayout(
sidebarPanel(
selectInput("Choices", label = "Choices",
choices = isolate(Data()[,1]),
selected = isolate(Data()[,1][[1]])
)
),
mainPanel(
renderTable({ Data() })
)
)
)
navbarPage("Analysis",
tabPanel("File Choice", panel1),
tabPanel("File Show", panel2))
```
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.