I am trying to save input from a checkbox table (see here) adapted from [here][2], once the actionButton has been clicked. Ideally, I would like a list of chosen boxes within one dataframe column, and the username as row name.
I tried it with the below syntax, by storing the responses in a list and then appending them to an existing csv.file.
library(shiny)
library(DT)
answer_options<- c("reading", "swimming",
"cooking", "hiking","binge- watching series",
"other")
question2<- "What hobbies do you have?"
shinyApp(
ui = fluidPage(
h2("Questions"),
p("Below are a number of statements, please indicate your level of agreement"),
DT::dataTableOutput('checkbox_matrix'),
verbatimTextOutput('checkbox_list'),
textInput(inputId = "username", label= "Please enter your username"),
actionButton(inputId= "submit", label= "submit")
),
server = function(input, output, session) {
checkbox_m = matrix(
as.character(answer_options), nrow = length(answer_options), ncol = length(question2), byrow = TRUE,
dimnames = list(answer_options, question2)
)
for (i in seq_len(nrow(checkbox_m))) {
checkbox_m[i, ] = sprintf(
'<input type="checkbox" name="%s" value="%s"/>',
answer_options[i], checkbox_m[i, ]
)
}
checkbox_m
output$checkbox_matrix= DT::renderDataTable(
checkbox_m, escape = FALSE, selection = 'none', server = FALSE,
options = list(dom = 't', paging = FALSE, ordering = FALSE),
callback = JS("table.rows().every(function(i, tab, row) {
var $this = $(this.node());
$this.attr('id', this.data()[0]);
$this.addClass('shiny-input-checkbox');
});
Shiny.unbindAll(table.table().node());
Shiny.bindAll(table.table().node());")
)
observeEvent(input$submit,{
# unlist values from json table
listed_responses <- sapply(answer_options, function(i) input[[i]])
write.table(listed_responses,
file = "responses.csv",
append= TRUE, sep= ',',
col.names = TRUE)
})
}
)
All I get is Warning in :
write.table(listed_responses, file = "responses.csv", append = TRUE, :appending column names to file
Besides the warning, nothing is being saved in the .csv file and I am not sure what exactly I am missing.
How do you correctly save a list of checked boxes from a datatable?