Hi Is there a way to append data to existing data in R. For example below application has dataframe populated based on user values , but right now, it is only creating new row and not appending.
Can we append this dataframe. I tried using reactive values as well. But did not work. Is there a way to achieve this?
library(shiny)
library(tidyr)
library(dplyr)
library(purrr)
ui <- basicPage(
fluidRow(
column(
width = 6,
textInput('a', 'Text A',"a1"),
textInput('b', 'Text B',"b1"),
textInput('c', 'Text A',"c1"),
textInput('d', 'Text B',"d1"),
textInput('e', 'Text A',"e1"),
textInput('f', 'Text B',"f1"),
uiOutput('f1')
),
column(
width = 6,
tags$p(tags$span(id = "valueA", "")),
tags$script(
"$(document).on('shiny:inputchanged', function(event) {
if (event.name === 'a') {
$('#valueA').text(event.value);
}
});
"
)
,tableOutput('show_inputs')
)
)
)
server <- shinyServer(function(input, output, session){
output$f1 <- renderUI({
if(input$a == "a2"){
textInput('z', 'Text B',"z1")
} else {
NULL
}
})
AllInputs <- reactive({
x <- reactiveValuesToList(input)
# print(x)
# data.frame(
# names = names(x),
# values = paste0(unlist(x, use.names = FALSE), Sys.time())
# )
tibble(
key = names(x),
data = x
) %>%
mutate(data = map(data, as.character)) %>%
unnest(data)
})
# observe({
# if(file.exists("file.csv")){
# write.table(AllInputs(), "file.csv", sep = ",", col.names = F, append = T, row.names = F)
# } else {
# write.csv(AllInputs(), "file.csv", sep = ",", row.names = F)
# }
#
# })
output$show_inputs <- renderTable({
t(AllInputs())
})
})
shinyApp(ui = ui, server = server)
CodePudding user response:
You need to maintain a reactiveVal
which holds your rows and to which you append on change:
library(shiny)
library(tidyr)
library(dplyr)
library(purrr)
ui <- basicPage(
fluidRow(
column(
width = 6,
textInput("a", "Text A","a1"),
textInput("b", "Text B","b1"),
textInput("c", "Text A","c1"),
textInput("d", "Text B","d1"),
textInput("e", "Text A","e1"),
textInput("f", "Text B","f1"),
uiOutput("f1")
),
column(
width = 6,
tags$p(tags$span(id = "valueA", "")),
tags$script(
"$(document).on('shiny:inputchanged', function(event) {
if (event.name === 'a') {
$('#valueA').text(event.value);
}
});"
),
tableOutput("show_inputs")
)
)
)
server <- shinyServer(function(input, output, session){
my_data <- reactiveVal(list(character(0)) %>%
rep(7) %>%
set_names(letters[c(1:6, 26)]) %>%
as_tibble())
output$f1 <- renderUI({
if(input$a == "a2"){
textInput("z", "Text B", "z1")
} else {
NULL
}
})
observe({
new_row <- reactiveValuesToList(input)
dat <- isolate(my_data())
my_data(bind_rows(dat, new_row))
})
output$show_inputs <- renderTable({
req(my_data())
})
})
shinyApp(ui = ui, server = server)
Please note that you will need some extra logic to avoid that the dynamic input$f1
still holds text if you change the value in input$a1
.