我是 R-Shiny 的新手,我的问题可能非常简单。经过几个小时的思考和搜索,我无法解决这个问题。问题是这样的:
1)我的应用程序要求用户上传他的数据集。
2)然后在服务器文件中,我读取数据集并进行了一些分析,然后将结果报告到用户界面中。
3)我的用户界面有 4 种不同的输出。
4)我在每个输出的“渲染”函数中读取数据集。问题:通过这样做,数据在每个函数的范围内本地定义,这意味着我需要读取对每个输出重复一遍。
5)这效率很低,有什么替代方案吗?使用响应式(Reactive)?
6) 下面是一个示例代码,展示了我如何编写我的服务器。R:
shinyServer(function(input, output) {
# Interactive UI's:
# %Completion
output$myPlot1 <- renderPlot({
inFile <- input$file
if (is.null(inFile)) return(NULL)
data <- read.csv(inFile$datapath, header = TRUE)
# I use the data and generate a plot here
})
output$myPlot2 <- renderPlot({
inFile <- input$file
if (is.null(inFile)) return(NULL)
data <- read.csv(inFile$datapath, header = TRUE)
# I use the data and generate a plot here
})
})
我怎样才能只获取一次输入数据并在输出函数中使用这些数据?
非常感谢,
最佳答案
您可以在响应式(Reactive)
函数中调用文件中的数据。然后可以访问它,例如
其他响应式(Reactive)
函数中的myData()
:
library(shiny)
write.csv(data.frame(a = 1:10, b = letters[1:10]), 'test.csv')
runApp(list(ui = fluidPage(
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv'))
),
mainPanel(
tableOutput('contents')
)
)
)
, server = function(input, output, session){
myData <- reactive({
inFile <- input$file1
if (is.null(inFile)) return(NULL)
data <- read.csv(inFile$datapath, header = TRUE)
data
})
output$contents <- renderTable({
myData()
})
}
)
)
关于r - 在 R Shiny 中处理输入数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24599141/