【发布时间】:2018-05-10 16:35:28
【问题描述】:
我创建了一个闪亮的应用程序,其中包括一个checkBoxGroup。调用时,此元素返回一个带有所选选项的向量。我可以使用 write.table() 将其写入文件,它会创建一个 CSV 文件,其中一行如下所示:
Jota 5 5 nature3 5 5 FALSE c("choice1", "choice2", "choice4") property c("choiceA", "choiceB", "ChoiceD", "choiceE", "choiceK") 5 5
但是使用read.table() 读回这个文件似乎很棘手,因为它会返回
扫描错误(文件 = 文件,什么 = 什么,sep = sep,quote = quote,dec = dec,: 第 9 行没有 12 个参数
我假设read.table() 难以解析 CSV 文件中的向量。除了展平结构并将每个选择转换为具有唯一列的单独的 TRUE/FALSE 值之外,还有其他解决方法吗?
编辑:示例应用
按照建议,我组装了一个虚拟应用程序来复制问题。它建立在 Shiny 的 article 之上。与上面描述的不同,它使用write.csv() 并为每个表单提交创建一个新文件,但问题是相同的。
library(shiny)
fields <- c("name", "groupInput")
shinyApp(
ui = fluidPage(
textInput("name", "Name", ""),
checkboxGroupInput("groupInput", "Select from list", choices = c('abc', 'def', 'ghi')),
actionButton("submit", "Submit"),
DT::dataTableOutput("responses", width = 300)
),
server = function(input, output, session) {
formData <- reactive({
data <- sapply(fields, function(x) input[[x]])
data
})
observeEvent(input$submit, {
saveData(formData())
})
output$responses <- DT::renderDataTable({
input$submit
loadData()
})
outputDir <- "responses"
saveData <- function(data) {
data <- t(data)
# Create a unique file name
fileName <- sprintf("%s_%s.csv", as.integer(Sys.time()), digest::digest(data))
# Write the file to the local system
write.csv(
x = data,
file = file.path(outputDir, fileName),
row.names = FALSE, quote = TRUE
)
}
loadData <- function() {
# Read all the files into a list
files <- list.files(outputDir, full.names = TRUE)
data <- lapply(files, read.csv, stringsAsFactors = FALSE)
# Concatenate all data together into one data.frame
data <- do.call(rbind, data)
data
}
}
)
当您运行它并在checkBoxGroup 中选中多个框时,将存储的 CSV 如下所示:
"name","groupInput"
somename,c("abc", "def", "ghi")
CSV中向量的存在似乎导致read.csv出错,即:
Warning: Error in read.table: more columns than column names
Stack trace (innermost first):
87: read.table
86: FUN
85: lapply
84: loadData [/Users/alexanderjulmer/Code/test-storage/app.R#45]
83: exprFunc [/Users/alexanderjulmer/Code/test-storage/app.R#25]
82: widgetFunc
81: func
80: origRenderFunc
79: renderFunc
78: origRenderFunc
77: output$responses
1: runApp
我认为这是因为在 data.frame 中没有正确解析向量,我怀疑这是可能的。所以我认为最好将checkBoxGroup中的数据分成几列。但是,那该怎么做呢?
【问题讨论】:
-
您能否提供您的
write.table()电话,并描述您希望通过重新读取文件的行为(或者更好的是,创建一个简单的工作应用程序来演示问题)?如果您想写入 CSV,我认为解决方法是将您的 checkBoxGroup 输入视为单个字符串。但是,问题还不清楚这是否对你有用。 -
我希望添加一个示例来澄清我的问题。我认为问题在于,
checkBoxGroup返回的向量在存储之前需要特殊处理。