【发布时间】:2023-03-26 03:14:01
【问题描述】:
我依靠找到here 的代码块来创建一个闪亮的应用程序来上传表格,编辑表格,然后下载表格。我已经设法编辑了一个已经加载到内存(iris)中的表格,但是如何编辑要在 Shiny 中上传的表格?。
我已经尝试了上面链接中的代码并验证它可以工作。我也尝试了下面的代码,这也有效。我无法实现的是将数据框x 转换为分配给上传文件的反应对象,并相应地编辑对x 的所有引用。
# This code works, but lacks a fileinput object
# and needs to be amended for a reactive dataframe...
library(shiny)
library(DT)
shinyApp(
ui = fluidPage(
fluidRow(
# ~~ add fileInput("file1", "Choose file") here ~~
downloadButton("download")
),
fluidRow(
DT::dataTableOutput('x1')
)
),
server = function(input, output, session) {
# Do I make x reactive?
x = iris
x$Date = Sys.time() + seq_len(nrow(x))
output$x1 = DT::renderDataTable(x, selection = 'none', rownames = FALSE, edit = TRUE)
proxy = dataTableProxy('x1')
observeEvent(input$x1_cell_edit, {
info = input$x1_cell_edit
str(info)
i = info$row
j = info$col + 1
v = info$value
x[i, j] <<- DT:::coerceValue(v, x[i, j])
replaceData(proxy, x, resetPaging = FALSE, rownames = FALSE)
})
output$download <- downloadHandler("example.csv",
content = function(file){
write.csv(x, file)
},
contentType = "text/csv")
}
)
之前的尝试都抛出了错误,主要是因为没有活动的反应上下文就不允许操作。
下面的代码显示了我想要实现的目标,但会引发错误: “缺少参数“expr”,没有默认值”
library(shiny)
library(DT)
shinyApp(
ui = fluidPage(
fluidRow(
fileInput("upload", "Choose CSV File",
multiple = FALSE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")),
downloadButton("download")
),
fluidRow(
DT::dataTableOutput('x1')
)
),
server = function(input, output, session) {
#x = iris
# In this edited example x is now a reactive expression, dependent on input$upload
x <- eventReactive({
# input$file1 will be NULL initially. After the user selects
# and uploads a file, head of that data file by default,
# or all rows if selected, will be shown.
req(input$upload)
# when reading semicolon separated files,
# having a comma separator causes `read.csv` to error
tryCatch(
{
x <- read.csv(input$upload$datapath,
header = TRUE,
sep = ",",
stringsAsFactors = TRUE,
row.names = NULL)
},
error = function(e) {
# return a safeError if a parsing error occurs
stop(safeError(e))
}
)
})
#x$Date = Sys.time() + seq_len(nrow(x))
output$x1 = DT::renderDataTable(x(), selection = 'none', rownames = FALSE, edit = TRUE)
proxy = dataTableProxy('x1')
observeEvent(input$x1_cell_edit, {
info = input$x1_cell_edit
str(info)
i = info$row
j = info$col + 1
v = info$value
x()[[i, j]] <<- DT:::coerceValue(v, x()[[i, j]])
newdf <- x()
replaceData(proxy, newdf, resetPaging = FALSE, rownames = FALSE)
})
output$download <- downloadHandler("example.csv",
content = function(file){
write.csv(x(), file)
},
contentType = "text/csv")
}
)
【问题讨论】:
-
我也尝试了here 的建议,但这引发了更多问题。然而,作者正试图做我想做的事。
-
您能否附上您使用
fileInput的尝试? -
当然。添加了新代码。