R 使用 shiny、rhandson 和 DT 更改列类型

R change columns types using shiny, rhandson and DT

我有一个闪亮的应用程序,用户可以将他的 csv 上传到 user_table() 反应式表达,然后使用 DT renderDataTable() 显示给用户; 还有 RHandsontable,其列类型来自 user_table()。用户应该能够更改 RHandsontable 中的值并单击 'Apply' 按钮,以将更改应用到他的 table。 (即有一个 'number' 列,他想将其更改为 'character')。 以下是为用户呈现 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() }
})

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

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

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 没有对用户输入做出反应;它只是将列类型更改为它们已经存在的类型。任何解决方法?

似乎是这样工作的:

  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()) })