我是R的新手,也许有人可以帮我解决有关闪亮问题的问题.
我想上传一个data.frame作为带闪亮的csv,之后我想通过一些计算来改变data.frame,然后我想用闪亮的应用程序再次下载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
Run Code Online (Sandbox Code Playgroud)
在闪亮的图库的帮助下,我的代码到目前为止看起来像这样:(我只是尝试上传csv并再次下载而不进行计算):
ui.R:
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')
)
)
)
Run Code Online (Sandbox Code Playgroud)
server.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)
}
)
Run Code Online (Sandbox Code Playgroud)
}
我可以上传一个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')
)
)
)
)
Run Code Online (Sandbox Code Playgroud)
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)
})
}
Run Code Online (Sandbox Code Playgroud)
shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)
如您所见,我创建了一个反应性对象来生成数据并将其保存。使用时,不要将数据保存在代码中的任何位置read.csv。您只需读取数据并将其输入,renderTable但数据不会保存在R中。从本质上讲,您需要保存数据并将其提供给其他ouput$...功能。这就是reactive这种情况。保存文件,并使其可用于其他输出功能。
有一个教程在这里