首页 > 解决方案 > 根据来自另一个 rhandon 表单元格的值更新 rhandson 表单元格

问题描述

我正在尝试根据用户在另一个 rhandson 表中引入的值更新 rhandson 表中的给定单元格。

基本上,我想从第一个表的第二列中提取第二个表的第二列中引入的值。

示例:我将值 50 放在表 2 的第一行预算列中,我希望从表 1 的第一行预算列中减去该值。

我从这里改编了这个例子:

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)

标签: rshinyrhandsontable

解决方案


在这种情况下,input$table2output$changes$changes将拥有修改您的其他表所需的信息。

尤其是:

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

请注意,这些是零索引的。

您可以包含一个if声明,以确保您仅根据预算列更改更改值,而不是日期等其他列。

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
)

推荐阅读