Nico Biagi
Nico Biagi

Reputation: 21

Renaming coulmns names of a reactive dataframe in Shiny

I have an R dataframe with several columns and I'd like users to select one column to plot against time. However, when I try to run this code, I get an error message.

country <- reactive({
    input$variable
})

date_start <- reactive({
    input$dateRange[1]
})

date_end <- reactive({
    input$dateRange[2]
})

new_data <- reactive({
    data[which(data$location== country() & data$date >= date_start() & data$date<=date_end()),c("date","location",input$info)]
    names(new_data()) <- c("date", "location", "col1")
})

The error is:

Error in names(new_data()) <- c("date", "location", "col1") : invalid (NULL) left side of assignment

Can anyone help me with that, please?

Upvotes: 1

Views: 804

Answers (1)

Shamis
Shamis

Reputation: 2604

This should do the trick:

new_data <- reactive({
    data_selection <- data[which(data$location== country() & data$date >= date_start() & data$date<=date_end()),c("date","location",input$info)]
    colnames(data_selection) <- c("date", "location", "col1")
    data_selection
})

You were referencing the reactive value inside the reactive call, which is then assigned to the new_data. Because this happens before the assignment, the value of the new_data within the call is null. Fortunately there is no need to do that.

Note: as you didn't post your data, I had no way to actually test your code. However here is a minimal working example to illustrate the concept:

library(shiny)

ui <- fluidPage(
    dataTableOutput("geysers")
)

server <- function(input, output) {
    test <- reactive({
        a <- faithful[1:3,]
        colnames(a) <- c("a", "b")
        a
    })
    output$geysers <- renderDataTable({test()})
}

shinyApp(ui = ui, server = server)

Upvotes: 1

Related Questions