我有一个简单的闪亮应用程序,我想将selectInput
中的值作为数据框的列名传递,并在ggplot中使用它。我的UI代码如下:
library(shiny)
# Define UI for application that draws a histogram
shinyUI(fluidPage(
# Application title
titlePanel("Title"),
# Sidebar with a slider input for the number of bins
sidebarLayout(
sidebarPanel(
selectInput(inputId = "yaxis",
label = "Y-axis",
choices = list("Overall Rank" = "overall_rank",
"Income Deprivation" = "income_deprivation_rank"),
selected = "income_deprivation_rank"),
selectInput(inputId = "xaxis",
label = "X-axis",
choices = list("Overall Rank" = "overall_rank",
"Income Deprivation" = "income_deprivation_rank"),
selected = "overall_rank")),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot"),
h5("Notes"),
p("notes")
)
)
))
我的服务器端代码变化很简单,我有一个SPARQL查询(在这里剪切以节省空间),创建简单的数据框:
# Libs
require(shiny); require(SPARQL); require(ggplot2)
# Server function
shinyServer(function(input, output) {
# Source the data
## Define endpoint URL.
endpoint <- "http://data.opendatascotland.org/sparql.csv"
### Create Query
query.simd <- "PREFIX stats: <http://statistics.data.gov.uk/id/statistical-geography/>
(...) cut to save space (...)"
## Make the data
dta.simd<- SPARQL(url = endpoint, query = query.simd, format = "csv")$results
## Make the plot
output$distPlot <- renderPlot({
xaxis <- as.character(input$xaxis)
yaxis <- as.character(input$yaxis)
# draw the the plot
ggplot(data = dta.simd, aes(x = xaxis, y = yaxis)) +
geom_point(shape=1)
})
})
查询产生一个简单的数据框,重新提取下面的摘录:
observation overall_rank income_deprivation_rank
a001 2 6
a002 10 7
a003 11 9
在编译应用程序后,我继续收到错误:对象'找不到xaxis'。这使我相信无论出于何种原因,input$xaxis
的值都不会传递给xaxis
对象,也不能在ggplot中使用。如果我决定将as.character(input$yaxis)
替换为与列名对应的字符串,例如overall_rank
和另一个income_deprivation_rank
,则应用程序可以正常工作,因此问题显然是关联的使用input$xaxis
值。我尝试了没有as.character()
函数的代码,但得到了相同的错误消息。
答案 0 :(得分:2)
在通常情况下,将列名引用为类似input$colName
的字符串时,请将其替换为get(input$colName)
。这样,Shiny就会知道获取input$colName
的值,而不是将其视为字符串。