【发布时间】:2018-07-04 03:01:20
【问题描述】:
为清楚起见进行了编辑:
我正在构建一个闪亮的应用程序来探索散点图中的数据。简化代码如下:
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)
我的问题是,当我选择列名(使用函数 colnames)作为 selectInput 函数中的选项,并且 colnames 包含空格(即“Year 12”而不是 Year12)时,我的散点图不起作用,给出错误信息:
错误::1:6: 意外'in' 1:出生于
代码示例
# Select variable for y-axis
selectInput(inputId = "y", label = "Y-axis:",
choices = colnames(Data[6:32])
现在,如果我为每个变量设置别名,例如使用以下代码,则应用程序可以正常工作:
# 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")
),
我的问题是 - 有没有一种方法可以更有效地为名称取别名,以便我可以自动化别名过程。我已经尝试了一些使用 names() 函数的 hack 方法,但到目前为止它只抛出了错误。
最终我可以手动解决这个问题,但肯定有更好的方法。
谢谢
编辑:
如果有帮助,我已经包含了一部分数据。您将不得不更改以下代码:
# Select variable for x-axis
selectInput(inputId = "x", label = "X-axis:",
choices = colnames(Data[6:32])
),
只是
choices = colnames(Data)
对于 X 和 Y 选择输入
数据:
> 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
【问题讨论】:
-
Using ggplot2 with columns that have spaces in their names 的可能重复项。问题出在
ggplot函数中。我会听取所提到的问答的建议,并确保您以有效的列名开头, -
这是一个类似的问题,但并不完全适用于这里。由于我在 Shiny 中创建应用程序,如果我为 ggplot 设置列名“有效”,则 selectInput 列表的名称对于普通人来说并不完全是用户友好的。如果我只是单独使用 ggplot 创建绘图,那将不是问题,因为我可以使用轴标签来规避问题。
-
我明白了。我认为约翰保罗的回答应该可以解决您的问题。或者,您可以重命名列(将空格替换为点或下划线),并使用
gsub将点替换为selectInput的空格。