我想通过用户定义的y轴的值来为我的R Shiny中的条形图排序x轴(名称)。
x_axis <- reactive({
as.data.frame <- lpop$Name <- reorder(lpop$Name, lpop$MYE2016,
FUN = mean)
})
上面的代码创建了一个反应式变量,该变量在MYE2016之前对伦敦自治市镇的名称进行排序。
用户可以在UI中选择y变量。如果我更改代码以包含输入变量(input $ y-从上面的代码中可能是MYE2016),如下所示:
x_axis <- reactive({
as.data.frame <- lpop$Name <- reorder(lpop$Name, input$y, FUN = mean)
})
我收到以下错误:
参数必须具有相同的长度
为什么会出现此错误?
完整代码在这里:
library(shiny)
library(readxl) # to load the data into R
library(tidyr) # to restructure the data
library(ggplot2) # for the barchart
library(dplyr) # to group and filter the data
library(stringr)
library(dplyr)
library(DT)
library(tools)
library(tidyverse)
library(forcats)
lpop <-read.csv("londonpopchange.csv", header=TRUE)
# Define UI for application that plots features of movies
ui <- fluidPage(
# Sidebar layout with a input and output definitions
sidebarLayout(
# Inputs
sidebarPanel(
# Select variable for y-axis
selectInput(inputId = "y",
label = "Y-axis:",
choices = c("Mid Year 2016" = "MYE2016",
"Births" = "Births"),
selected = "MYE2016"),
# Select variable for x-axis
selectInput(inputId = "x",
label = "X-axis:",
choices = c("Borough" = "Name"),
selected = "Name")
),
# Output
mainPanel(
plotOutput(outputId = "geom_bar")
)
)
)
# Define server function required to create the scatterplot
server <- function(input, output) {
# reactive should update when the y axis variable is changed
# this reorders borough name, by select y axis variable, using mean
x_axis <- reactive({
as.data.frame <- lpop$Name <- reorder(lpop$Name, input$y, FUN = mean)
})
# Create the scatterplot object the plotOutput function is expecting
output$geom_bar <- renderPlot({
ggplot(data = lpop, aes_string(x = x_axis(), y = input$y)) +
geom_bar(stat = "identity") +
theme(axis.text.x = element_text(angle = 90))
})
}
# Create a Shiny app object
shinyApp(ui = ui, server = server)
可以在这里找到数据集:https://www.dropbox.com/s/apez4tyzdm3qjp8/londonpopchange.csv?dl=0
暂时保持简单