我使用光泽进行了一次简单的调查,该调查需要一些用户输入。我想将调查结果下载为csv文件。这是我目前所拥有的:
library(shiny)
library(DT)
# Define UI for survey
ui <- fluidPage(
# Application title
titlePanel("Pet Survey"),
# Sidebar with a selector and checkboxes
sidebarLayout(
sidebarPanel(
selectInput("type",
"Type:",
c("Cat" = 1,
"Dog" = 2)
),
checkboxGroupInput(inputId="size",
label = "Size",
choices = list("Small" = "small",
"Medium" = "medium",
"Large" = "large"),
selected = NULL)
),
mainPanel(
HTML("Download data"),
br(), br(),
downloadButton("download_data", "Download data")
)
)
# Define server logic
server <- function(input, output) {
# Download file
output$download_data <- downloadHandler(
filename = ("response.csv"),
content = function(file) {
write_csv(response %>% select(input$selected_var), path = file)
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
当我运行并单击下载按钮时,它另存为txt文件。我只是不确定用户输入数据的结构。从本质上讲,我希望获得一个看起来像这样的表:
Dog, Cat, Small, Medium, Large
1, 0, 0, 1, 0
这意味着用户选择了“狗”并选中了“中”复选框
答案 0 :(得分:1)
这是一个有效的server
函数
# Define server logic
server <- function(input, output) {
# Download file
output$download_data <- downloadHandler(
filename = ("response.csv"),
content = function(file) {
write_csv(data.frame(Dog= ifelse(input$type==2,1,NA),
Cat= ifelse(input$type==1,1,NA),
Small= ifelse(input$size=='small',1,NA),
Medium= ifelse(input$size=='medium',1,NA),
Larg= ifelse(input$size=='size',1,NA)),
path = file)
}
)
}
复选框组输入控件的描述是创建一组可用于独立切换多个选项的复选框,因此我们可以创建一个reactiveValues
来保存所选选项并将其切换为使用observeEvent
的“非独立”选择。
library(shiny)
library(DT)
# Define UI for survey
ui <- fluidPage(
# Application title
titlePanel("Pet Survey"),
# Sidebar with a selector and checkboxes
sidebarLayout(
sidebarPanel(
selectInput("type",
"Type:",
c("Cat" = 1,
"Dog" = 2)
),
checkboxGroupInput(inputId="size",
label = "Size",
choices = list("Small" = "small",
"Medium" = "medium",
"Large" = "large"),
selected = NULL)
),
mainPanel(
HTML("Download data"),
br(), br(),
dataTableOutput('tbl'),
actionButton('go',"Save"),br(),br(),
downloadButton("download_data", "Download data")
)
))
# Define server logic
server <- function(input, output, session) {
observe(print(input$size))
data <- reactiveValues()
observeEvent(input$go,{
data$size <- input$size
data$table <- data.frame(Dog= ifelse(input$type==2,1,NA),
Cat= ifelse(input$type==1,1,NA),
Small= ifelse(c('small') %in% data$size,1,NA),
Medium= ifelse(c('medium') %in% data$size,1,NA),
Larg= ifelse(c('large') %in% data$size,1,NA))
})
output$tbl <- renderDataTable(data$table)
# Download file
output$download_data <- downloadHandler(
filename = ("response.csv"),
content = function(file) {
write_csv(data$table,path = file)
}
)
}
# Run the application
shinyApp(ui = ui, server = server)