I am trying to add an editable datatable in r shiny. I have two components to it. First being allowing the user to add a new row and delete a selected row. Secondly when the user changes any value in the cell it should update the corresponding cell. The issue I am facing is if the user edits column dd
it should update the value for column ff
based on the formula. Also when I edit a cell and add new rows the new columns come up as blanks. How can I fix this.Thank you.
### Libraries
library(shiny)
library(dplyr)
library(DT)
### Data
input_data <- data.frame(aa = c("Brand1", "Brand2","Brand3"),
bb = c(2000, 3000, 4000),
cc = c (.5, .5, .5),
dd = c(2000, 3000, 4000),
ee = c (.5, .5, .5),
ff = c (.5, .5, .5),
gg = c (.5, .5, .5),
stringsAsFactors = FALSE)
### Shiny App
shinyApp(
ui = basicPage(
mainPanel(
actionButton("reset", "Reset"),
actionButton("add_btn", "Add"),
actionButton("delete_btn", "Delete"),
tags$hr(),
DT::dataTableOutput("mod_table") )
),
server = function(input, output) {
#demodata<-input_data
this_table <- reactiveVal(input_data)
observeEvent(input$add_btn, {
t = rbind(data.frame(aa = "default",
bb = 1000000,cc = 2.0,dd = 20000, ee = 40,ff = 00 , gg = 00), this_table())
this_table(t)
})
observeEvent(input$delete_btn, {
t = this_table()
print(nrow(t))
if (!is.null(input$shiny_table_rows_selected)) {
t <- t[-as.numeric(input$shiny_table_rows_selected),]
}
this_table(t)
})
observeEvent(input$mod_table_cell_edit, {
v <- this_table()
# #
proxy = dataTableProxy("mod_table")
print(names(v$data))
info = input$mod_table_cell_edit
str(info)
i = info$row
j = info$col
k = info$value
str(info)
# #
isolate(
if (j %in% match(c("aa","bb","cc","dd","ee","ff","gg"), names(v$data))) {
# print(match(c("ratio","cost", "updated_price"), names(v$data)))
v$data[i, j] <<- DT::coerceValue(k, v$data[i, j])
print(v$data)
# #
# #
if (j %in% match("reach_percentage", names(v$data))) {
v$data$ff <<- v$data$dd / 10000
}
} else {
stop("You are not supposed to change this column.") # check to stop the user from editing only few columns
}
)
replaceData(proxy, v$data, resetPaging = FALSE) # replaces data displayed by the updated table
})
#
observeEvent(input$reset, {
this_table <- input_data # your default data
})
# #
output$mod_table <- DT::renderDataTable({
datatable(this_table(), selection = 'single',editable = TRUE, options = list(dom = 't'))
})
}
)