2017-09-03 53 views
0

我從多個來源拉取大型數據集,並且在保存數據以供進一步處理之前需要重命名某些列。下面給出的是我迄今爲止的代表性R腳本。我需要關於如何交互重命名列的建議。在Rshiny中交互重命名列

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

如果你想修改數據,你需要將它存儲在某個地方; 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) 
    }) 
}