问题描述
我正在尝试根据用户在另一个rhandson表中引入的值来更新rhandson表中的给定单元格。
基本上,我想从第一张表的第二列中提取第二张表的第二列中引入的值。
示例:我将值50放在表格2的第一行“预算”列中,并希望从表1的第一行“预算”中减去该值。
我改编了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,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)
},ignoreNULL = TRUE
)
}
shinyApp(ui = ui,server = server)
解决方法
在这种情况下,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
)