如何指定文件和路径以使用 R-shiny 和 shinyFiles 保存文件? [英] How to specify file and path to save a file with R-shiny and shinyFiles?

查看:52
本文介绍了如何指定文件和路径以使用 R-shiny 和 shinyFiles 保存文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 R(闪亮)并希望将数据框保存为 excel 文件.为此,我使用shinyFiles"包,以便用户可以指定 excel 文件的存储位置:

I am working with R (shiny) and want to save a dataframe as an excel file. For this purpose I use the "shinyFiles" package so that the user can specify where the excel file is to be stored:

服务器.R图书馆(闪亮)库(闪亮文件)

server.R library(shiny) library(shinyFiles)

shinyServer(function(input, output, session) {

## ShinyFiles : get the user favorite directory
volumes=c(home = '~/'),
shinyDirChoose(input, 'dir', roots=volumes, filetypes = c('','xlsx')),
output$dir.res <- renderPrint({parseDirPath(volumes, input$dir)}),

## Button to save the file
observeEvent(input$button.save, {

## A standard file name
A <- "name"
B <- "family
if( input$text == "File name..." ) outFile <- paste( A, "_", B, ".xlsx", sep="" )

## Append the path to the file name
outFile <- paste( parseDirPath(volumes, input$path.out), outFile, sep="/" )

## The data to be saved
x=seq(from=0,to=10,by=1)
d = data.frame( x )
write.xlsx( d, outFile )
}

和 ui.R

library(shiny)
library(shinyFiles)

shinyUI(fluidPage(sidebarLayout(

## Choose the output directory
shinyDirButton("dir", "Choose directory", "Upload"),
## Choose the output file name
textInput("text", label = "", value = "File name..."),
## Save the data
actionButton("button.save", "Save the file"),
## Give the path selected
verbatimTextOutput("dir.res")
)))

尽管找到了所有类似问题的示例,但我已经尝试了 2 小时(耻辱..),并将感谢您的帮助

Despite all the examples found for similar questions I have been trying around for 2h (shame..) and will be thankful for help

推荐答案

这是一个工作示例.同样,这假设您在自己的计算机上运行应用程序,并且允许用户访问此计算机上的文件夹.您可以设置允许用户保存文件的根文件夹(参见UserFolder,用户将能够选择该根目录的任何子文件夹)

Here is a working example. Again, this assumes that you run the app on your own computer, and users are allowed to access folders on this computer. You can set the root folder where user is allowed to save files (see UserFolder, user will be able to choose any subfolder of this root)

library(shiny)
library(shinyFiles)
library(xlsx)

ui <- shinyUI(fluidPage(

  titlePanel("Example"),
  shinySaveButton("save", "Save file", "Save file as ...", filetype=list(xlsx="xlsx"))

))

server <- shinyServer(function(input, output, session) {

  observe({
    volumes <- c("UserFolder"="D:/Data")
    shinyFileSave(input, "save", roots=volumes, session=session)
    fileinfo <- parseSavePath(volumes, input$save)
    data <- data.frame(a=c(1,2))
    if (nrow(fileinfo) > 0) {
      write.xlsx(data, as.character(fileinfo$datapath))
    }
  })
})

shinyApp(ui = ui, server = server)

这篇关于如何指定文件和路径以使用 R-shiny 和 shinyFiles 保存文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆