Я разрабатываю блестящее приложение для интерактивного создания таблицы с именами файлов и некоторым новым текстом или комментарием для каждого из них. В настоящее время он работает следующим образом:
1. выбор папки
2. создание файла .csv с именами файлов (если их нет)
Имя файла .csv соответствует шаблону "subfolderName". csv
3. Выбор имени файла с помощью параметра selectInput
4. Добавление ваших комментариев для каждой строки (файла) в файл .csv во второй столбец с именем «комментарии»
Некоторое желаемое поведение, которое я не смог сделать:
- Показать предыдущий комментарий, если он есть, для текущего выбранного имени файла (сохраненный в .csv) в текстовом поле (комментарий написан). Я также пробовал updateTextInput и не работал.
#save as app.R
library(shiny)
library(shinyFiles)
library(shinyBS)
library(dplyr)
ui <- fluidPage(sidebarLayout(
sidebarPanel(
shinyDirButton("dir", "1. Choose directory", "Upload")
,br(),br()
, bsButton("submit","2. Create or reset .csv", style="warning")
,br(),br()
, uiOutput("fileinput")
, uiOutput("uitextinput") # this is not showing existing comments
, bsButton("addname","4. Add comment", style="warning")
),
mainPanel(
h4("Selected folder"),
verbatimTextOutput("dirtext"), br(),
h4("Files in that dir"),
verbatimTextOutput("files"),
textOutput("result")
)
))
path1<-"~"
server <- function(input, output, session) {
output$result<-renderText({
t<- reac$message
})
shinyDirChoose(input, 'dir', roots = c(home = path1) )
reacdir <- reactive(input$dir)
output$dirtext <- renderPrint(c(path(),current() ) )
path <- reactive({
home <- normalizePath(path1)
file.path(home, paste(unlist(reacdir()$path[-1]), collapse = .Platform$file.sep))
})
current<-reactive({
a<-sub('.*\\/', '', path() )
b<-paste("current subdir:",a)
})
reac <- reactiveValues(comment=NULL, df2=NULL)
#not WORKING
output$uitextinput<-renderUI(
textInput("commentwritten","Comment for file", reac$comment)
)
# GET current .csv file with comments and load the comment to reac$comment , Not working
observe({
validate(
need(try(any(class(reactiveFileReader(1000, session, paste0(path(),"/",sub('.*\\/', '', path() ),".csv") ,
read.csv()))=="data.frame")==TRUE), "Wait 801")
)
reac$df2<- reactiveFileReader(1000, session, paste0(path(),"/",sub('.*\\/', '', path() ),".csv") , read.csv, stringsAsFactors=FALSE)
reac$comment<-reac$df2$comment[match(input$file, reac$df2$name)]
})
filedata<-reactive({
filenames<- list.files(path())
filedata<-data.frame(name=filenames)
})
# button 2. creating the csv file
observeEvent(input$submit,{
write.csv(filedata(), file =paste0(path(),"/",sub('.*\\/', '', path() ),".csv") , row.names = FALSE )
})
#step 3
output$fileinput<-renderUI(
div(style="width: 100%; margin: 0 0;",
selectInput("file", "3. Select filename to add details", filedata()$name)
)
)
#step 4, adding a comment to the .csv
observeEvent(input$addname , {
if(file.exists(paste0(path(),"/",sub('.*\\/', '', path() ),".csv")) ){
dfnameadded <- reactive({
originaldf<-reactiveFileReader(1000, session, paste0(path(),"/",sub('.*\\/', '', path() ),".csv") , read.csv, stringsAsFactors=FALSE)
filetoadd <- data.frame(name=input$file , stringsAsFactors = FALSE)
filetoadd$comment<-input$commentwritten
l<-list(originaldf(),filetoadd)#
dfadded<- Reduce(bind_rows, l)
dfadded<-dfadded %>%
group_by(name) %>%
summarise(comment = paste0(na.omit(comment[length(comment)]), collapse = "; ") )
dfadded
})
tryCatch(write.csv(dfnameadded(), file =paste0(path(),"/",sub('.*\\/', '', path() ),".csv") , row.names = FALSE ),
error = function(e) {print(paste("create .csv first")) ; "create .csv first" } )
reac$message<-"comment added"
}
else
{
reac$message<-"create .csv first"
}
})
output$files <- renderPrint(list.files(path()))
} # end server
shinyApp(ui, server)