【发布时间】:2021-07-11 00:53:32
【问题描述】:
我正在尝试上传 csv 文件或 rds 文件,并将其用作创建表的数据集。我尝试使用条件if/else,但出现此错误:argument is of length zero。我想将它上传到渲染表之外,因为我也想将反应数据集用于其他目的。
代码
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file_csv", "Choose CSV File", accept = ".csv"),
checkboxInput("header", "Header", TRUE),
fileInput("file_rds", "Choose RDS File", accept = ".rds"),
),
mainPanel(
tableOutput("table1")
)
)
)
server <- function(input, output) {
dataset <- reactive({
if(input$file_csv) {
file <- input$file_csv
ext <- tools::file_ext(file$datapath)
req(file)
validate(need(ext == "csv", "Please upload a csv file"))
read.csv(file$datapath, header = input$header)
} else {
readRDS(file_rds$datapath)
}
})
output$table1 <- renderTable({
head(dataset())
})
}
shinyApp(ui = ui, server = server)
尝试使用observeEvent(不起作用):
output$table1 <- renderTable({
req(dataset())
head(dataset())
})
observeEvent(input$file_csv, {
dataset <- read.csv(input$file_csv$datapath, header = input$header)
})
observeEvent(input$file_rds, {
dataset <- readRDS(input$file_rds$datapath)
})
尝试 rds 文件(不工作):
if(!is.null(input$file_rds )) {
file <- input$file_rds
req(file)
readRDS(file$datapath)
}
【问题讨论】:
-
if(input$file_csv)在这里不是逻辑条件,因为input$file_csv可以为空或字符串值 -
我通常用
req(input$file_csv)开始这样的反应,因为它可以排除大多数这样的问题。 -
我尝试添加
req(input$file_csv),但它没有解决 akrun 指出的逻辑问题。在这种情况下,什么是好的逻辑条件? -
我猜你可能需要
is.nullwrapped -
我尝试了另一种方法,但没有奏效。请查看更新。