R - 用DT和闪亮的数字转换数字字符变量

时间:2018-03-29 01:08:01

标签: r datatables shiny dt

我试图在数字中动态转换字符变量已经过了2天,反之亦然。

在这里,我向您发送一个可复制的例子:

library(DT)
library(shiny)
library(tidyverse)

server = shinyServer(function(input, output) {


  mydata <- reactive({
    df <- mtcars %>% rownames_to_column("model")
    df[,2] <- ifelse(input[[paste0("col", 2)]]=="num",unlist(df[,2]) %>% 
    as.numeric, unlist(df[,2]) %>% as.character)
    df 
  })


  output$tableau <- DT::renderDT({
    #df <- mtcars %>% rownames_to_column("model")
    df <- mydata()
    class <- map_df(df, typeof)
    class <- gsub("double", "numeric", class)
    class <- gsub("integer", "numeric", class)
    tableSelectInput <- map(1:ncol(df),
                        function(i) {
                          if (class[i] =="numeric"){
                            opt1 <- "num"
                            opt2 <- "cat"
                          }else{ 
                            opt1 <- "cat"
                            opt2 <- "num"
                          }
                          selectInput(
                            inputId = paste0("col", i),
                            label = NULL, selected = opt1,
                            choices = c(opt1, opt2))
                        }
  ) 

  # I didn't find a more elegant way to turn '[[ ]]' in '[ ]'
  l <-  length(tableSelectInput)
  selectin  <-  1:l
  type_cat <-  1:l
  for (i in 1:l) {
    selectin[i] = as.character(tableSelectInput[[i]])
    pos=gregexpr("selected>",selectin[i])[[1]][1]
    type_cat[i] = substr(selectin[i],(pos+9),(pos+11))
  }
  col_names = paste0(colnames(df), " <br/><em>(",type_cat,")</em> 
  <br/>", selectin, sep=" ")

  DT::datatable(
    df,
    options = list(
    preDrawCallback = JS("function() { 
      Shiny.unbindAll(this.api().table().node()); }"),
    drawCallback = JS("function() { Shiny.bindAll(this.api().table().node()); 
    }")
  ),
  colnames =col_names, 
  editable = TRUE,
  escape=FALSE,
  selection = list(target = 'column'))
  }, server=FALSE)



output$log <- renderPrint({
  #To check if it works
  mydata()[,2]
  })
})

ui = shinyUI(
  fluidPage(
  titlePanel("My Awesome Shiny App"),

   # Show a plot of the generated distribution
   mainPanel(
   DT::DTOutput("tableau"),
   # Show log
   verbatimTextOutput("log")
   )
  )
) 
runApp(list(ui = ui, server = server))

问题: 当我尝试更改2列的selectinput时。在renderPrint中,我们看到格式的类型不会改变。 有人可以帮我吗?

0 个答案:

没有答案