【问题标题】:R Shiny App: Reactive/Calculate column in RhandsontableR Shiny App:Rhandsontable 中的反应/计算列
【发布时间】:2017-05-20 17:30:09
【问题描述】:

我正在使用 Rhansontable 包,我想创建一个表,如果我在其中更改一列中的值,则另一列会自动计算。例如:

DF = data.frame(num = 1:10, price = 1:10,stringsAsFactors = FALSE)

在上面的数据框中,当我更改“num”列中的值时,应自动计算另一列“Total”(num*price)

能否提供示例闪亮代码的帮助?

【问题讨论】:

    标签: shiny


    【解决方案1】:

    我想这就是你想要的

    #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)
    

    【讨论】:

    • 谢谢@Pork Chop,你的回答很有帮助。但是,我注意到当我们刷新页面时,修改就消失了。我们如何保留修改后的值?
    猜你喜欢
    • 2017-10-19
    • 2021-05-26
    • 2021-02-17
    • 1970-01-01
    • 2017-01-17
    • 2017-04-21
    • 2020-06-26
    • 2019-04-07
    • 2020-04-23
    相关资源
    最近更新 更多