我是 R 的新手,也许有人可以帮助我解决有关 Shiny 的问题。
我想将 data.frame 上传为带有 Shiny 的 csv,之后我想通过一些计算更改 data.frame,然后我想使用 Shiny 的应用程序再次下载 data.frame。假设我有一个数据框:
x <- data.frame(value1=c(1:100), value2=c(101:200)) #data frame I uploaded
x$value2 <- x$value2/x$value1 # calculation
# then download it
在 Shiny 画廊的帮助下,我的代码到目前为止看起来像这样:(我只尝试上传一个 csv 并再次下载它而没有计算):
用户界面:
library(shiny)
fluidPage(
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
tags$hr(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),
','),
radioButtons('quote', 'Quote',
c(None='',
'Double Quote'='"',
'Single Quote'="'"),
'"'),
downloadButton('downloadData', 'Download')
),
mainPanel(
tableOutput('contents')
)
)
)
服务器.R:
library(shiny)
function(input, output) {
output$contents <- renderTable({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
read.csv(inFile$datapath, header=input$header, sep=input$sep,
quote=input$quote)
})
output$downloadData <- downloadHandler(
filename = function() {
paste(input$file1, '.csv', sep='')
},
content = function(file) {
write.csv(file1, file)
}
)
}
我可以上传一个csv,这没问题,但下载不起作用,我没有引用上传的文件..
有人现在有答案或可以在这里帮助我吗?也许这是一个愚蠢的错误,但我五天前开始使用 R,这对我来说是全新的。
非常感谢!!
最佳答案
以下对我有用:
用户界面
ui <- fluidPage(
fluidPage(
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
tags$hr(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),
','),
radioButtons('quote', 'Quote',
c(None='',
'Double Quote'='"',
'Single Quote'="'"),
'"'),
downloadButton('downloadData', 'Download')
),
mainPanel(
tableOutput('contents')
)
)
)
)
服务器
server <- function(input, output) {
getData <- reactive({
inFile <- input$file1
if (is.null(input$file1))
return(NULL)
read.csv(inFile$datapath, header=input$header, sep=input$sep,
quote=input$quote)
})
output$contents <- renderTable(
getData()
)
output$downloadData <- downloadHandler(
filename = function() {
paste("data-", Sys.Date(), ".csv", sep="")
},
content = function(file) {
write.csv(getData(), file)
})
}
跑
shinyApp(ui, server)
正如你所看到的,我创建了一个 react 对象来生成数据并保存它。当您使用
read.csv
时,您不会在代码中的任何位置保存数据。 .您只需读取数据并将其提供给 renderTable
但数据并未保存在 R 中。本质上,您需要保存数据并使其可供其他人使用 ouput$...
职能。这是什么reactive
在这种情况下。保存文件并使其可用于其他输出功能。有教程here
关于r - 使用 Shiny 的包上传数据、更改数据框和下载结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41856577/