在一个闪亮的应用程序中将动态 Dataframe 的选定列的类转换为数值

k10s72fa  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(114)

我有下面的shiny应用程序,其中我显示了initial Dataframe 的所有列名以及表中的class()
我想做的是选择一列,然后按actionButton()将其转换为numeric。在这种情况下,我们选择case_id
新的数据集是initial2,但它必须是可用的,即使我们将它的一个变量转换为numeric或不转换。
此外,在按下actionButton()后,表中包含case_id类的类应从character转换为numeric
Dataframe 可能每次都不同。

## app.R ##
library(shiny)
library(shinydashboard)
library(DT)
library(tibble)
library(tidyverse) # for the tibble
initial<-structure(list(case_id = c("3397364", "3397364"), action = c("3397364-RAAMELK", 
                                                                      "3397364-RAAMELK"), resource = c("RAAMELK", "RAAMELK"), lifecycle = c(1, 
                                                                                                                                            1), registration_type = structure(1:2, .Label = c("start", "complete"
                                                                                                                                            ), class = "factor"), timestamp = structure(c(1667523600, 1667531220
                                                                                                                                            ), tzone = "UTC", class = c("POSIXct", "POSIXt")), activity = c("RAAMELK", 
                                                                                                                                                                                                            "RAAMELK"), activity_description = c("Forbrukt r<e5>melk", "Forbrukt r<e5>melk"
                                                                                                                                                                                                            ), ...9 = c(NA, NA), product = c("K101152", "K101152"), product_type_text = c("200100 - Milk", 
                                                                                                                                                                                                                                                                                          "200100 - Milk"), qty = c(NA, 31), in_out = c("in", "out"), qty_scrap = c(NA_real_, 
                                                                                                                                                                                                                                                                                                                                                                    NA_real_), `FP ordre` = c(NA_character_, NA_character_), Artikkeltype = c("SF", 
                                                                                                                                                                                                                                                                                                                                                                                                                                              "SF"), .order = 1:2), row.names = c(NA, -2L), class = c("eventlog", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      "log", "tbl_df", "tbl", "data.frame"), case_id = "case_id", activity_id = "activity", activity_instance_id = "action", lifecycle_id = "registration_type", resource_id = "resource", timestamp = "timestamp")
shinyApp(
  ui = dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody(
      dataTableOutput("dt0"),
      dataTableOutput("dt"),
      selectInput("cols","Select column to convert",choices = colnames(initial),multiple = F,selected =colnames(initial)[1] ),
      actionButton("conv","Convert to numeric")
    )
  ),
  server = function(input, output, session) { # add session so we can update

initial<-reactive({
validate(
  need(!is.null(input$file1), 'No data exists, please upload a csv')
)
# p<-read.csv(inFile$datapath, header = T,sep = 
#input$separator,na.strings=c("",".","NA"))
   })   

     output$dt0<-renderDataTable({
      
      datatable(initial)
    }) 
    output$dt<-renderDataTable({
      
      dat<-data.frame(tibble(Name = colnames(initial), Class = sapply(initial, function(x) 
        paste(class(x), collapse=", "))))
      
      datatable(dat)
    }) 
    initial2<-reactive({input$conv
      initial #after processing or not
    })
  }
)
f3temu5u

f3temu5u1#

一种选择是使用reactiveVal,你可以用你的initial数据集初始化它。reactiveVal可以在你的renderDataTable中,并通过由actionButton触发的observeEvent更新。对于转换,我使用lapply,它允许在需要时一次转换多个列。

library(shiny)
library(shinydashboard)
library(DT)
library(tibble)
library(tidyverse)

shinyApp(
  ui = dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody(
      dataTableOutput("dt0"),
      dataTableOutput("dt"),
      selectInput("cols", "Select column to convert", choices = colnames(initial), multiple = F, selected = colnames(initial)[1]),
      actionButton("conv", "Convert to numeric")
    )
  ),
  server = function(input, output, session) { # add session so we can update
    dat <- reactiveVal(initial)
    
    output$dt0 <- renderDataTable({
      datatable(dat())
    })
    
    output$dt <- renderDataTable({
      dat <- data.frame(tibble(Name = colnames(dat()), Class = sapply(dat(), function(x) {
        paste(class(x), collapse = ", ")
      })))

      datatable(dat)
    })
    
    observeEvent(input$conv, {
      x <- dat()
      x[input$cols] <- lapply(x[input$cols], as.numeric)
      dat(x)
    })
  }
)

编辑一个选项是将reactiveVal初始化为空 Dataframe 。然后使用observeEvent等来上传数据,并使用上传的数据初始化reactiveVal。例如,我向应用添加了fileInput

shinyApp(
  ui = dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody(
      fileInput("upload", "Upload a file"),
      dataTableOutput("dt0"),
      dataTableOutput("dt"),
      selectInput("cols", "Select column to convert", choices = NULL, multiple = F),
      actionButton("conv", "Convert to numeric")
    )
  ),
  server = function(input, output, session) { # add session so we can update
    dat <- reactiveVal(data.frame())
    
    observeEvent(input$upload, {
      dat(read.csv(input$upload$datapath))
      
      updateSelectInput(inputId = "cols", choices = colnames(dat()), selected = colnames(dat())[[1]])
    })
    
    output$dt0 <- renderDataTable({
      datatable(dat())
    })
    
    output$dt <- renderDataTable({
      dat <- data.frame(tibble(Name = colnames(dat()), Class = sapply(dat(), function(x) {
        paste(class(x), collapse = ", ")
      })))

      datatable(dat)
    })
    
    observeEvent(input$conv, {
      x <- dat()
      x[input$cols] <- lapply(x[input$cols], as.numeric)
      dat(x)
    })
  }
)

相关问题