【发布时间】:2020-01-10 17:37:25
【问题描述】:
我有几个表存储在一个单独的 txt 文件中,并且还合并在一个 Rdat 文件中,如下所示:
# generate tables
df.A <- data.frame(colA1=letters[1:20],colA2=LETTERS[1:20], stringsAsFactors = F)
df.B <- data.frame(colB1=rnorm(20),colB2=rnorm(20), stringsAsFactors = F)
# save tables as separate files
write.csv(df.A, 'tableA.txt')
write.csv(df.B, 'tableB.txt')
# I may have more tables
# save all tables in a single Rdat file
save(df.A,df.B, file = 'alldata.RDat')
现在在我闪亮的 Markdown 文档中,我想从 RDat 文件中预加载这些表,但也让用户可以重新加载它们 a) 与单个文件分开,或 b) 完全从 RDat文件。这是我来到的第一个版本:
---
runtime: shiny
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
load('alldata.RDat')
```
Tables below:
```{r}
inputPanel(
actionButton('load.A','Reload Table A'),
actionButton('load.B','Reload Table B'),
actionButton('load.Rdat','Load all from Rdat file')
)
tabsetPanel(type = "tabs",
tabPanel("table A", dataTableOutput("toA")),
tabPanel("table B", dataTableOutput("toB"))
)
# next 2 lines render pre-loaded tables before any buttons are pressed:
output$toA <- renderDataTable(df.A, options=list(pageLength=5))
output$toB <- renderDataTable(df.B, options=list(pageLength=5))
observeEvent(input$load.A, {
df.A <- read.csv('tableA.txt');
output$toA <- renderDataTable(df.A, options=list(pageLength=5))
})
observeEvent(input$load.B, {
df.B <- read.csv('tableB.txt');
output$toB <- renderDataTable(df.B, options=list(pageLength=5))
})
observeEvent(input$load.Rdat, {
load('alldata.RDat', verbose = T);
output$toA <- renderDataTable(df.A, options=list(pageLength=5));
output$toB <- renderDataTable(df.B, options=list(pageLength=5))
})
```
它工作得很好,但我觉得这不是使用反应性的正确方法。例如,每次更新我的表对象(df.A 或dfB)后,我都必须显式调用render output$toA <- renderDataTable(...)(每个表3 次!)。
我想到的一个解决方案是将我的表格放入reactiveValues(),它给出了以下内容:
---
runtime: shiny
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
load('alldata.RDat')
```
Tables below:
```{r}
inputPanel(
actionButton('load.A','Reload Table A'),
actionButton('load.B','Reload Table B'),
actionButton('load.Rdat','Load all from Rdat file')
)
tabsetPanel(type = "tabs",
tabPanel("table A", dataTableOutput("toA")),
tabPanel("table B", dataTableOutput("toB"))
)
rv <- reactiveValues(df.A = df.A, df.B = df.B)
output$toA <- renderDataTable(rv$df.A, options=list(pageLength=5))
output$toB <- renderDataTable(rv$df.B, options=list(pageLength=5))
observeEvent(input$load.A, {
rv$df.A <- read.csv('tableA.txt');
})
observeEvent(input$load.B, {
rv$df.B <- read.csv('tableB.txt');
})
observeEvent(input$load.Rdat, {
load('alldata.RDat', verbose = T);
rv$df.A <- df.A;
rv$df.B <- df.B;
})
```
这看起来更好,因为我的代码中每个 renderDataTable() 都只有一个调用。但是现在我的每个表都存储在内存中两次——一个在df.A(从'alldata.RDat'加载)和另一个在rv$df.A...这是否有意义,或者有更犹太的方式解决这些问题?
【问题讨论】:
标签: r shiny reactive shiny-reactivity