Javascript Shinny R:如何保存来自datatable的复选框输入列表?
单击actionButton后,我试图保存从[here][2]改编的复选框表()中的输入。理想情况下,我希望在一个dataframe列中列出所选框的列表,并将用户名作为行名 我尝试了以下语法,将响应存储在一个列表中,然后将它们附加到现有的csv.file文件中Javascript Shinny R:如何保存来自datatable的复选框输入列表?,javascript,r,shiny,Javascript,R,Shiny,单击actionButton后,我试图保存从[here][2]改编的复选框表()中的输入。理想情况下,我希望在一个dataframe列中列出所选框的列表,并将用户名作为行名 我尝试了以下语法,将响应存储在一个列表中,然后将它们附加到现有的csv.file文件中 library(shiny) library(DT) answer_options<- c("reading", "swimming", "cooking", "hiking","bing
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)
})
}
)
库(闪亮)
图书馆(DT)
回答选项错误消息
错误源于在对write.table
的同一调用中使用col.names=TRUE
和append=TRUE
。例如:
write.table(mtcars, "test.csv", append = TRUE, sep = ",", col.names = TRUE)
# Warning message:
# In write.table(mtcars, "test.csv", append = TRUE, sep = ",", col.names = TRUE) :
# appending column names to file
write.table
希望您知道它正在向csv添加一行列名。由于您可能不希望在每组答案之间有一行列名,因此当col.names=FALSE
时,只使用append=TRUE
可能更为简洁。您可以使用if…else
编写两种不同的表单来保存csv,一种用于创建文件,另一种用于附加后续响应:
if(!file.exists("responses.csv")) {
write.table(responses,
"responses.csv",
col.names = TRUE,
append = FALSE,
sep = ",")
} else {
write.table(responses,
"responses.csv",
col.names = FALSE,
append = TRUE,
sep = ",")
}
空csv
您的csv为空是因为您的复选框没有作为输入正确绑定。我们可以通过在应用程序中添加以下行来了解这一点:
server = function(input, output, session) {
...
output$print <- renderPrint({
reactiveValuesToList(input)
})
}
ui = fluidPage(
...
verbatimTextOutput("print")
)
完整示例
下面是两个修复的示例。我还添加了modals,以在用户成功提交表单或缺少用户名时提醒用户。提交表格后,我将其清除
library(shiny)
library(DT)
shinyApp(
ui =
fluidPage(
# style modals
tags$style(
HTML(
".error {
background-color: red;
color: white;
}
.success {
background-color: green;
color: white;
}"
)),
h2("Questions"),
p("Please check if you enjoy the activity"),
DT::dataTableOutput('checkbox_table'),
br(),
textInput(inputId = "username", label= "Please enter your username"),
actionButton(inputId = "submit", label= "Submit Form")
),
server = function(input, output, session) {
# create vector of activities
answer_options <- c("reading",
"swimming",
"cooking",
"hiking",
"binge-watching series",
"other")
### 1. create a datatable with checkboxes ###
# taken from https://github.com/rstudio/DT/issues/93/#issuecomment-111001538
# a) function to create inputs
shinyInput <- function(FUN, ids, ...) {
inputs <- NULL
inputs <- sapply(ids, function(x) {
inputs[x] <- as.character(FUN(inputId = x, label = NULL, ...))
})
inputs
}
# b) create dataframe with the checkboxes
df <- data.frame(
Activity = answer_options,
Enjoy = shinyInput(checkboxInput, answer_options),
stringsAsFactors = FALSE
)
# c) create the datatable
output$checkbox_table <- DT::renderDataTable(
df,
server = FALSE, escape = FALSE, selection = 'none',
rownames = FALSE,
options = list(
dom = 't', paging = FALSE, ordering = FALSE,
preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')
)
)
### 2. save rows when user hits submit -- either to new or existing csv ###
observeEvent(input$submit, {
# if user has not put in a username, don't add rows and show modal instead
if(input$username == "") {
showModal(modalDialog(
"Please enter your username first",
easyClose = TRUE,
footer = NULL,
class = "error"
))
} else {
responses <- data.frame(user = input$username,
activity = answer_options,
enjoy = sapply(answer_options, function(i) input[[i]], USE.NAMES = FALSE))
# if file doesn't exist in current wd, col.names = TRUE + append = FALSE
# if file does exist in current wd, col.names = FALSE + append = TRUE
if(!file.exists("responses.csv")) {
write.table(responses, "responses.csv",
col.names = TRUE,
row.names = FALSE,
append = FALSE,
sep = ",")
} else {
write.table(responses, "responses.csv",
col.names = FALSE,
row.names = FALSE,
append = TRUE,
sep = ",")
}
# tell user form was successfully submitted
showModal(modalDialog("Successfully submitted",
easyClose = TRUE,
footer = NULL,
class = "success"))
# reset all checkboxes and username
sapply(answer_options, function(x) updateCheckboxInput(session, x, value = FALSE))
updateTextInput(session, "username", value = "")
}
})
}
)
库(闪亮)
图书馆(DT)
shinyApp(
用户界面=
流动摄影(
#风格情态动词
标签$style(
HTML(
“.错误{
背景色:红色;
颜色:白色;
}
.成功{
背景颜色:绿色;
颜色:白色;
}"
)),
h2(“问题”),
p(“请检查您是否喜欢该活动”),
DT::dataTableOutput('checkbox_table'),
br(),
textInput(inputId=“username”,label=“请输入您的用户名”),
操作按钮(inputId=“提交”,label=“提交表单”)
),
服务器=功能(输入、输出、会话){
#创建活动向量
答:非常感谢您的时间作出回应。它正是我想做的事情!JKHUC乐于助人,欢迎使用堆栈溢出。如果这个答案解决了您的问题,请考虑将其标记为接受。
library(shiny)
library(DT)
shinyApp(
ui =
fluidPage(
# style modals
tags$style(
HTML(
".error {
background-color: red;
color: white;
}
.success {
background-color: green;
color: white;
}"
)),
h2("Questions"),
p("Please check if you enjoy the activity"),
DT::dataTableOutput('checkbox_table'),
br(),
textInput(inputId = "username", label= "Please enter your username"),
actionButton(inputId = "submit", label= "Submit Form")
),
server = function(input, output, session) {
# create vector of activities
answer_options <- c("reading",
"swimming",
"cooking",
"hiking",
"binge-watching series",
"other")
### 1. create a datatable with checkboxes ###
# taken from https://github.com/rstudio/DT/issues/93/#issuecomment-111001538
# a) function to create inputs
shinyInput <- function(FUN, ids, ...) {
inputs <- NULL
inputs <- sapply(ids, function(x) {
inputs[x] <- as.character(FUN(inputId = x, label = NULL, ...))
})
inputs
}
# b) create dataframe with the checkboxes
df <- data.frame(
Activity = answer_options,
Enjoy = shinyInput(checkboxInput, answer_options),
stringsAsFactors = FALSE
)
# c) create the datatable
output$checkbox_table <- DT::renderDataTable(
df,
server = FALSE, escape = FALSE, selection = 'none',
rownames = FALSE,
options = list(
dom = 't', paging = FALSE, ordering = FALSE,
preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')
)
)
### 2. save rows when user hits submit -- either to new or existing csv ###
observeEvent(input$submit, {
# if user has not put in a username, don't add rows and show modal instead
if(input$username == "") {
showModal(modalDialog(
"Please enter your username first",
easyClose = TRUE,
footer = NULL,
class = "error"
))
} else {
responses <- data.frame(user = input$username,
activity = answer_options,
enjoy = sapply(answer_options, function(i) input[[i]], USE.NAMES = FALSE))
# if file doesn't exist in current wd, col.names = TRUE + append = FALSE
# if file does exist in current wd, col.names = FALSE + append = TRUE
if(!file.exists("responses.csv")) {
write.table(responses, "responses.csv",
col.names = TRUE,
row.names = FALSE,
append = FALSE,
sep = ",")
} else {
write.table(responses, "responses.csv",
col.names = FALSE,
row.names = FALSE,
append = TRUE,
sep = ",")
}
# tell user form was successfully submitted
showModal(modalDialog("Successfully submitted",
easyClose = TRUE,
footer = NULL,
class = "success"))
# reset all checkboxes and username
sapply(answer_options, function(x) updateCheckboxInput(session, x, value = FALSE))
updateTextInput(session, "username", value = "")
}
})
}
)