簡體   English   中英

R 使用閃亮、rhandson 和 DT 更改列類型

[英]R change columns types using shiny, rhandson and DT

我有一個閃亮的應用程序,用戶可以在其中將他的 csv 上傳到user_table()反應式表達式中,然后使用 DT renderDataTable()將其顯示給用戶; 還有來自user_table()的列類型的user_table() 用戶應該能夠更改 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 不會對用戶輸入做出反應; 它只是將列類型更改為與它們已經相同的類型。 任何解決方法?

似乎是這樣工作的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM