reactive variable renaming in Rshiny

Can someone explain to me why this code, which works fine in R gives me errors (or simply does not work in Rshiny). After creation of a tibble I want to rename certain variables (actually variables in multiple tibbles, hence the use of a reactive() enviroment. The new name is based on multiple inputs that are pased together I realize that the solution given here might fix this specifc instance, but for the app I am buidling it would not, as my renaming is not only based on a user input, but on some other events as well. af

This is the normal R code that does work

library(tidyverse)
X1 <- "My"
X2 <- "var"

header <- paste0(X1, X2)

mtcars %>%
  as_tibble() %>%
  rename(!!header := mpg) %>%
  head()

but this does not work in Shiny

library(tidyverse)
library(shiny)


ui <- fluidPage(
    textInput("Part_1", "first part var name"),
    textInput("Part_2", "second part var name"),
    tableOutput("result")
)

server <- function(input, output, session) {
    
    header <- reactive({
        paste0(input$Part_1, input$Part_2)
    })
    
    output$result <- renderTable({
        mtcars %>%
            as_tibble() %>%
            rename(!!header() := mpg) %>%
            head()
    })
}

shinyApp(ui, server)

your app starts up without work-able values in the two textInputs, this would be equivalent to the plain r script

library(tidyverse)
X1 <- ""
X2 <- ""

header <- paste0(X1, X2)

mtcars %>%
  as_tibble() %>%
  rename(!!header := mpg) %>%
  head()

you can address this by using req() or validate()/need() (and probably in other ways also)

1 Like

You are right, I thought I had set a default value in my actual app, but clearly didn't. Thanks!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.