在Rshiny中以交互方式重命名列

时间:2017-09-03 23:27:41

标签: r shiny

我从多个来源中提取大量数据集,需要在保存数据之前重命名一些列以供进一步处理。下面是我迄今为止的代表性R脚本。我需要有关如何以交互方式重命名列的建议。

library(shiny)
library(DT)

mtcars
write.csv(mtcars, "mtcars.csv", row.names = T)
ui <- shinyUI(fluidPage(
  title = "Rename Column",
  sidebarLayout(
    sidebarPanel(
      numericInput("Cylinder","Enter Cylinder", 8, min = 4, max = 12),
      actionButton("process", "Filter Data", style = "color: #fff; background-color: FORESTGREEN; border-color: #2e6da4"),
      tags$br(),tags$br(),
      selectInput(inputId = "OldColumnName", label = "Select Column Name to rename",multiple = F, choices = c("Nil"), selected = ""),
      textInput(inputId = "NewColumnName", label = "Enter New Column Name", "Nil"),
      actionButton("RenameColumn", "Rename Column",style = "color: #fff; background-color: MAROON; border-color: #2e6da4"),
      width = 3),

    mainPanel(wellPanel(
      tabsetPanel(type = "pills",  tabPanel("Data Table", 
                   DT::dataTableOutput("ResultsTable", width = "auto", height = "auto"),
                   style = "overflow-y:scroll; max-height: 900px")
      ))) 
    )))

server <- function(input,session, output){session$onSessionEnded(stopApp)

  df <- eventReactive(input$process, { 
        df <- data.frame(read.csv("mtcars.csv", header = T) )
        subset(df, df$cyl == input$Cylinder)
  })

  output$ResultsTable <- DT::renderDataTable({ 
    df <- df()
    if (!is.null(input$RenameColumn) & (input$NewColumnName != "Nil" | !is.null(input$NewColumnName))) 
       {names(df)[names(df) == input$OldColumnName] <- input$NewColumnName}
    updateSelectInput(session, "OldColumnName", choices = colnames(df), selected = NULL)
    DT::datatable(df)
  })
}

shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:1)

如果要修改数据,则需要将其存储在某处; reactiveValues个对象对此有好处。尝试这样的事情:

server <- function(input,session, output){session$onSessionEnded(stopApp)

  store <- reactiveValues()
  store$df <- mtcars

  observeEvent(input$process, { 
    df <- data.frame(read.csv("mtcars.csv", header = T) )
    store$df <- df[df$cyl == input$Cylinder,]
  })

  observeEvent(store$df, {
    updateSelectInput(session, "OldColumnName", choices = colnames(store$df),
                      selected = NULL)
  })

  observeEvent(input$RenameColumn, {
    req(input$NewColumnName, input$OldColumnName)
    if (input$NewColumnName != "Nil") {
      colnames(store$df)[colnames(store$df) == input$OldColumnName] <- 
        input$NewColumnName
      }
  })

  output$ResultsTable <- DT::renderDataTable({ 
    req(store$df)
    DT::datatable(store$df)
  })
}