Edited for clarity:
I'm building an app in shiny to explore data in a scatterplot. The simplified code is below:
library(shiny)
library(ggplot2)
library(DT)
library(tools)
library(dplyr)
library(tidyverse)
#load data
Data <- Electorate_Data
# Define UI for application
ui <- fluidPage(
titlePanel("Scatterplot"),
br(),
# Sidebar layout with a input and output definitions
sidebarLayout(
# Inputs
sidebarPanel(
# Select variable for y-axis
selectInput(inputId = "y", label = "Y-axis:",
choices = colnames(Data[6:32])
),
# Select variable for x-axis
selectInput(inputId = "x", label = "X-axis:",
choices = colnames(Data[6:32])
),
width = 6
),
# Output:
mainPanel(
# Create a container for tab panels
tabsetPanel(
tabPanel(
title = "Explore the Data",
# Show scatterplot
plotOutput(outputId = "scatterplot")
)
),
width = 6
)
)
)
# Define server function required to create the scatterplot
server <- function(input, output) {
# Create scatterplot object the plotOutput function is expecting
output$scatterplot <- renderPlot({
ggplot(data = Data, aes_string(x = input$x, y = input$y)) +
geom_point()
})
}
# Create a Shiny app object
shinyApp(ui = ui, server = server)
My issue is, when I select the column names (using the function colnames) to be the choices in the selectInput function, and the colnames contain spaces (i.e. "Year 12" instead of Year12), my scatterplot doesn't work, giving the error message:
Error: :1:6: unexpected 'in' 1: Born in
Code Example
# Select variable for y-axis
selectInput(inputId = "y", label = "Y-axis:",
choices = colnames(Data[6:32])
Now, if I alias each variable, for example using the following code, the app works perfectly fine:
# Select variable for y-axis
selectInput(inputId = "y", label = "Y-axis:",
choices = "Year12" = "Year 12",
"Born_Aus" = "Born in Australia",
"NoSchool" = "% of the Population Above 15 Years of Age that Didn't Attend School")
),
My question is - is there a way to alias the names more efficiently in such a way that I can automate the aliasing process. I've tried a few hack approaches using the names() function, but so far it has only thrown up errors.
At the end of the day I can solve this manually, but surely there is a better way.
Thanks
Edit:
I've included a subset of the data if that helps. You would have to change the code of:
# Select variable for x-axis
selectInput(inputId = "x", label = "X-axis:",
choices = colnames(Data[6:32])
),
to just
choices = colnames(Data)
for both the X and Y selectInputs
Data:
> head(Electorate_Data[14:18])
Born in Australia LOTE NoSchool Year12 Median_age
1 0.6126271 0.29805068 0.012132744 0.5481394 36
2 0.6419959 0.27278743 0.006160949 0.4610346 39
3 0.8234175 0.05199925 0.002323880 0.3564276 40
4 0.5633673 0.45200442 0.011578501 0.4933828 38
5 0.8186847 0.06066808 0.005270832 0.2701636 44
6 0.4439803 0.59099798 0.017304021 0.5374834 35