'Select column from dataframe using shiny widget and modify its name using textInput()

In the app below I want to select a column name from the selectInput() and then modify it using the textInput().The update will happen after the actionButton click.

library(shiny)
library(shinydashboard)
library(DT)
iris2 <- iris # make a copy, don't want mess up internal dataset 

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    fileInput("file1", "Choose CSV File",
              accept = c(
                "text/csv",
                "text/comma-separated-values,text/plain",
                ".csv")
    ),
    uiOutput("column"),
    textInput("text", label = "Set column name", placeholder = "Enter text..."),
    actionButton("sub","submit")
  ),
  dashboardBody(
    
    dataTableOutput("process")
  )
)

server <- function(input, output) {
  raw<-reactive({
    
    inFile <- input$file1
    
    if (is.null(inFile))
      return(NULL)
    
    read.csv(inFile$datapath, header = T)
  })
  raw2<-reactive({
    
    inFile <- input$file1
    
    if (is.null(inFile))
      return(NULL)
    
    read.csv(inFile$datapath, header = T)
  })
  output$column<-renderUI({
    selectInput("col","Pick a column to change its name",
                choices = colnames(raw2()))
  })
  mydf <- reactiveValues(df = raw2(), names = names(raw2()))
  
  observeEvent(input$sub, {
    req(input$text)
    mydf$names[mydf$names == input$col] <- input$text
    names(mydf$df) <- mydf$names
    updateSelectInput(inputId = "col", choices = mydf$names)
  })
  output$process<-renderDataTable({
    mydf$df
  })
}

shinyApp(ui, server)    


Solution 1:[1]

Here is how to fix

library(shiny)
library(shinydashboard)
library(DT)
iris2 <- iris # make a copy, don't want mess up internal dataset 

ui <- dashboardPage(
    dashboardHeader(),
    dashboardSidebar(
        selectInput("col","Pick a column to change its name",
                    choices = colnames(iris2)),
        textInput("text", label = "Set column name", placeholder = "Enter text..."),
        actionButton("sub","submit")
    ),
    dashboardBody(
        tags$style(type="text/css",
                   ".shiny-output-error { visibility: hidden; }",
                   ".shiny-output-error:before { visibility: hidden; }"
        ),
        dataTableOutput("process")
    )
)

server <- function(input, output) {
    mydf <- reactiveValues(df = iris2, names = names(iris2))
    
    observeEvent(input$sub, {
        req(input$text)
        mydf$names[mydf$names == input$col] <- input$text
        names(mydf$df) <- mydf$names
        updateSelectInput(inputId = "col", choices = mydf$names)
    })
    output$process<-renderDataTable({
        mydf$df
    })
}

shinyApp(ui, server)

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lz100