Reputation: 862
I am pulling a large data set from several sources, and need to rename some of the columns before saving data for further processing. Given below is a representative R script I have so far. I need advice on how to rename the column interactively.
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)
Upvotes: 0
Views: 1298
Reputation: 1758
If you want to modify the data, you need to store it somewhere; reactiveValues
objects are good for that. Try something like this:
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)
})
}
Upvotes: 2