【问题标题】:R change columns types using shiny, rhandson and DTR 使用闪亮、rhandson 和 DT 更改列类型
【发布时间】:2017-10-26 02:38:03
【问题描述】:

我有一个闪亮的应用程序,用户可以将他的 csv 上传到user_table() 反应式表达,然后使用 DT renderDataTable() 向用户显示; 还有来自user_table() 的列类型的RHandsontable。用户应该能够更改 RHandsontable 中的值并单击“应用”按钮,以将更改应用到他的表。 (即有一个“数字”列,他想将其更改为“字符”)。 以下是为用户呈现 DT 的方式:

main_table <- DT::renderDataTable({
    datatable(
        user_table()
    )
})

handsontable 的工作原理如下:

dataTypes <- c("integer", "numeric", "factor", "character", "logical")
handsontable <- renderRHandsontable({
    if (!is.null(input$uploaded_file)) {
        if (is.null(input$hottest)) {
            DF = data.frame(Type = cbind(lapply(user_table(), typeof)),
                            stringsAsFactors = TRUE)
        } else {
            DF = hot_to_r(input$hottest)
        }
        DF$Type = factor(DF$Type, dataTypes)
        rhandsontable(DF, readOnly = FALSE) %>%
            hot_table(stretchH = 'all', rowHeaderWidth = 120) %>%
            hot_context_menu(allowRowEdit = FALSE, allowColEdit = FALSE)
    }
    else { return() }
})

现在我正在尝试执行以下操作:单击应用按钮后,使用用户更改的列类型创建一个新表,但我不确定应该如何正确完成。我应该使用另一个反应式表达来做到这一点吗? observeEvent 是用于按钮 onclick 事件的正确方法吗?如果有不清楚的地方,请询问。提前致谢!

编辑:我在浏览了一段时间后想出了这个功能:

convert.types <- function(obj, types){
        for(i in length(obj)){
            func <- switch(types[i],
                           integer = as.integer,
                           numeric = as.numeric,
                           factor = as.factor,
                           character = as.character,
                           logical = as.logical)
            obj[,i] <- func(obj[,i])
        }
        obj
    }

并将其与 observeEvent 一起使用:

observeEvent(input$button_table_convertion, {
    hottestVector <- as.vector(t(hot_to_r(input$hottest)))
    new_table <- convert.types(as.data.frame(user_table()), hottestVector)

虽然,Rhandsontable 不会对用户输入做出反应;它只是将列类型更改为与它们已经相同的类型。有什么解决方法吗?

【问题讨论】:

    标签: r shiny dt rhandsontable


    【解决方案1】:

    似乎是这样工作的:

      new_table <- eventReactive(input$button_table_convertion, {
                hottestVector <- as.vector(t(hot_to_r(input$handsontypes)))
                convert.types(data.frame(user_table()), hottestVector)
            })
      output$secondtable <- DT::renderDataTable({ datatable(new_table()) })
    

    【讨论】:

      猜你喜欢
      • 2016-01-02
      • 2017-07-25
      • 2021-09-02
      • 2017-03-06
      • 2020-02-03
      • 2021-11-19
      • 2021-08-28
      • 1970-01-01
      • 2021-04-13
      相关资源
      最近更新 更多