我的Shiny应用程序存在一个问题。首先,我有两个dataframes
,其中有两个numeric
列(number
和number2
)。我也有动态的ui sliderInput
。闪亮的应用程序工作正常,直到...当我选择Item
数据框时,在number
中选择Y-axis variable
并在range
之间设置sliderInput
15和18之后,我想将Y-axis variable
更改为number2
我收到错误:
Error in eval(substitute(expr), envir, enclos) : wrong result size (2), expected 0 or 1
我知道问题是由于number2
列中的数字介于1和10之间而导致的,之前的设置不包括这些数字。谁能告诉我如何改进它?
ui.R
library(ggvis)
shinyUI(fluidPage(
titlePanel(""),
sidebarLayout(
sidebarPanel(
radioButtons("dataset", label = h4("Choose dataframe"),
choices = list("Item" = "df1", "Task" = "df2")),
selectInput("yvar", "Y-axis variable", axis_vars_y, selected = "number"),
uiOutput("slider")
),
mainPanel(
ggvisOutput("plot")
)
)
))
server.R
library(shiny)
library(dplyr)
library(magrittr)
library(lazyeval)
df1_number <-sample(seq(1,20,0.01),20,replace = T)
df2_number <-sample(seq(1,20,0.01),20,replace = T)
df1_number2 <-sample(seq(1,10,0.01),20,replace = T)
df2_number2 <-sample(seq(1,10,0.01),20,replace = T)
df1 <- data.frame(name = rep(letters[1:4],each = 5), number = df1_number, number2 = df1_number2)
df2 <- data.frame(name = rep(letters[1:4],each = 5), number = df2_number, number2 = df2_number2)
axis_vars_y <- c("number" = "number", "number2" = "number2")
shinyServer(function(input, output) {
datasetInput <- reactive({
switch(input$dataset,
df1 = df1,
df2 = df2)
})
axis_vara_y <- reactive({
switch(input$yvar,
number = 2,
number2 = 3)
})
output$slider <- renderUI({
sliderInput("inslider","Slider", min = min(datasetInput()[,axis_vara_y()]),
max = max(datasetInput()[,axis_vara_y()]),
value = c(min(datasetInput()[,axis_vara_y()]),
max(datasetInput()[,axis_vara_y()])),
step = 0.5)
})
data <- reactive({
filteredData <- datasetInput()
if(!is.null(input$inslider)){
filteredData <- filteredData %>%
filter(filteredData[,axis_vara_y()] >= input$inslider[1],
filteredData[,axis_vara_y()] <= input$inslider[2])
}
filteredData
})
data_two <- reactive({
data() %>%
mutate(id = 1:n())
})
vis <- reactive({
yvar_name <- names(axis_vars_y)[axis_vars_y == input$yvar]
yvar <- prop("y", as.symbol(input$yvar))
data_two %>%
ggvis(x = ~name, y = yvar) %>%
layer_points(size := 120,
fill = ~name,
fillOpacity := 0.6,
key := ~id)
})
vis %>% bind_shiny("plot")
})
更新 --------------------------------------- -------------------------------------------------- ----------
当我设置的范围不包含error
列中的任何值(例如,在13和14之间)时,会出现相同的number
。
答案 0 :(得分:4)
正如您所知,您收到的错误是因为过滤的数据集没有行。一个简单的解决方法是返回完整的数据集。这将重置inputSlider
以便您继续正常工作而不会出错。您只需要更改您的被动data
功能。
data <- reactive({
filteredData <- datasetInput()
axisData <- axis_vara_y()
if(!is.null(input$inslider)){
filteredData <- filteredData %>%
filter(filteredData[,axisData] >= input$inslider[1],
filteredData[,axisData] <= input$inslider[2])
}
# the new part to reset the slider
if(nrow(filteredData) == 0){
return(datasetInput())
}else{
return(filteredData)
}
})
我可以自由地简化代码,因为您可以分配您的被动数据语句,而不是让闪亮的应用程序多次调用它们。