guir
guir

Reputation: 69

update rhandson table cell based on value from another rhandon table cell shiny

I am trying to update a given cell in rhandson table, based on value introduced by the user in another rhandson table.

Basically, I would like to extract the value introduced in the second column of the second table, from the second column of the first table.

Example: I put the value 50 in the first row, column Budget of table2, and I want the value to be subtracted from the first row, column Budget of table 1.

I adapted the example from here:

library(shiny)
library(rhandsontable)

channel <- c("Budget")
start.date <- as.Date("2017-01-01")
end.date <- as.Date("2017-01-03")
date.range1 <- as.Date((seq(start.date,end.date,by="day")), origin = "1970-01-01")
date.range1 <- as.data.frame(date.range1)

date.range2 <- as.Date((seq(start.date,end.date,by="day")), origin = "1970-01-01")
date.range2 <- as.data.frame(date.range2)

colnames(date.range1) <- c("date")
colnames(date.range2) <- c("date")

date.range1[channel] <- 1000
date.range2[channel] <- 0

table1 <- date.range1
table2 <- date.range2
#Define the tables.

ui <- fluidPage(
  br(),
  fluidRow(
    column(4, rHandsontableOutput("table1output")),
    column(4, rHandsontableOutput("table2output"))
  ))

server <- function(input,output,session){
  table <- reactiveValues()
  table$table1 <- table1
  table$table2 <- table2
  
  #Define the tables
  
  output$table1output <- renderRHandsontable({rhandsontable(table$table1)})
  output$table2output <- renderRHandsontable({rhandsontable(table$table2)})
  
  observeEvent(input$table1output,{
    df <- hot_to_r(input$table1output)
    df <- as.data.frame(df)
    #table$table1 <- df
  }, ignoreInit = TRUE, ignoreNULL = TRUE
  )
  
  observeEvent(input$table2output,{
    df <- hot_to_r(input$table2output)
    df <- as.data.frame(df)
  }, ignoreInit = TRUE, ignoreNULL = TRUE
  )
  
}

shinyApp(ui = ui, server = server)

Upvotes: 1

Views: 499

Answers (1)

Ben
Ben

Reputation: 30539

In this case, input$table2output$changes$changes will have the information needed to modify your other table.

In particular:

# [[1]][[1]] will have the row edited 
# [[1]][[2]] will have the column edited 
# [[1]][[4]] will have the new value

Note that these are zero-indexed.

You can include an if statement to make sure you only change values based on budget column changes, and not other columns like the date.

observeEvent(input$table2output,{
  df <- hot_to_r(input$table2output)
  df <- as.data.frame(df)
    
  table_changes <- input$table2output$changes$changes
    
  if (!is.null(table_changes[[1]][[2]]) && table_changes[[1]][[2]] == 1) {
    table$table1[table_changes[[1]][[1]] + 1, table_changes[[1]][[2]] + 1] <- table$table1[table_changes[[1]][[1]] + 1, table_changes[[1]][[2]] + 1] - table_changes[[1]][[4]]
  }
}, ignoreInit = TRUE, ignoreNULL = TRUE
)

Upvotes: 2

Related Questions