R Shiny应用程序:Rhandsontable中的响应式/计算列

6
我正在使用Rhansontable包,想创建一个表格,其中如果我更改一列中的值,则另一列会自动计算。例如:
DF = data.frame(num = 1:10, price = 1:10,stringsAsFactors = FALSE)
在上述数据框中,当我更改“num”列中的值时,“Total”(num*price)应该自动计算。
请提供一个简单的shiny代码样例,可以帮助我实现这个功能吗?
1个回答

7

我认为这就是你想要的

#rm(list = ls())
library(shiny)
library(rhandsontable)

## Create the dataset
DF = data.frame(num = 1:10, price = 1:10,Total = 1:10,stringsAsFactors = FALSE)
numberofrows <- nrow(DF)

server <- shinyServer(function(input, output, session) {

  # Initiate your table
  previous <- reactive({DF})

  MyChanges <- reactive({
    if(is.null(input$hotable1)){return(previous())}
    else if(!identical(previous(),input$hotable1)){
      # hot.to.df function will convert your updated table into the dataframe
      mytable <- as.data.frame(hot_to_r(input$hotable1))
      # here the second column is a function of the first and it will be multipled by 100 given the values in the first column
      mytable <- mytable[1:numberofrows,]

      # Add some test cases
      mytable[,1][is.na(mytable[,1])] <- 1
      mytable[,2][is.na(mytable[,2])] <- 1
      mytable[,3] <- mytable[,1]*mytable[,2]
      mytable
    }
  })
  output$hotable1 <- renderRHandsontable({rhandsontable(MyChanges())})
})

ui <- basicPage(mainPanel(rHandsontableOutput("hotable1")))
shinyApp(ui, server)

enter image description here


谢谢@Pork Chop,你的回答非常有帮助。然而,我注意到当我们刷新页面时,修改的值会消失。我们如何保留修改后的值? - John Smith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接