【发布时间】:2018-04-13 01:31:05
【问题描述】:
我希望有人可以就解决我遇到的问题提供一些指导。作为背景,我正在尝试为用户创建一个界面来上传新闻报道的 csv,然后他们可以将其注释为相关或不相关,以用于分类。用户上传 csv 后应该出现的是带有可选行的表格输出。与所选行关联的文本将显示在右下方。
我尝试的设置是将用户上传的电子表格放入一个 reactive(),然后将其作为 eventReactive() 的一部分用于注释句子是否相关。但是,当我运行应用程序时,该表没有出现,并且没有错误或警告消息。我尝试修改我的方法以在加载 csv 时使用 reactiveValues() 和 observe(),但我遇到了同样的问题。我已经包含了下面的代码,以及一个玩具数据集。
过去几个小时我一直在网上搜索解决方案,但运气不佳。任何指导将不胜感激!
数据
sample <- data.frame(relevant = c('','','','',''), lede=c('first lede', 'second lede', 'third lede', 'fourth lede', 'fifth lede'))
write.csv(sample, 'sample.csv', row.names=F)
应用代码
library(shiny)
library(DT)
#######################################################
### INTERFACE
#######################################################
in1 <- radioButtons("truefalse", "Change values in 'keep' column here",
choices=c("TRUE", "FALSE"),
selected = "TRUE", inline = FALSE)
in2 <- actionButton("goButton", "Update Table")
in3 <- downloadButton("download_data", label = "Download")
in4 <- fileInput('datafile', 'Choose CSV file',
accept=c('text/csv', 'text/comma-separated-values,text/plain'))
out1 <- textOutput("text")
out2 <- dataTableOutput("sheet", width = "30%")
in5 <- textInput("save_file", "New file name:", value="updated_data.csv")
in6 <- actionButton("save", "Save updated data")
ui <- fluidPage(titlePanel("Text Annotater"),
column(6, out2),
column(6, in4, in1, in2, in5, in6, out1))
#######################################################
### SERVER
#######################################################
server <- function(input, output){
sheet <- reactive({
infile <- input$datafile
if (is.null(infile)) {
# User has not uploaded a file yet
return(NULL)
}
tbl = read.csv(infile$datapath, stringsAsFactors = FALSE)
return(tbl)
})
# reactive dataframe object
df <- eventReactive(input$goButton, {
if(selected_row_id()>0 &&input$goButton>0){
sheet()[selected_row_id(),1] <<- input$truefalse
}
sheet()
}, ignoreNULL = FALSE)
# selectable data table
output$sheet <- renderDataTable({
df()
}, selection = "single")
# selected row ID from data table
selected_row_id <- reactive({
input$sheet_rows_selected
})
# text of article
output$text<-renderText({sheet()[input$sheet_rows_selected, "lede"]})
# Save when click the button
observeEvent(input$save, {
write.csv(df, input$save_file, row.names = FALSE)
})
# download button
output$download_data <- downloadHandler(
filename = "updated_data.csv",
content = function(file) {
write.csv(df(), file, row.names = FALSE)
}
)
}
shinyApp(ui = ui, server = server)
【问题讨论】:
-
我认为您应该将所有
reactives 放在eventReactive之外,因为您始终可以检查input$goButton(在您的情况下)是否在reactive函数内触发。此外,您不会为eventReactive内的输出渲染任何内容,请使用ObserveEvent进行渲染。