Shiny: квантили не работают в реактивном контексте

У меня возникают проблемы с использованием quantile для получения процентилей указанной пользователем переменной в приложении Shiny, которое я пишу, и с использованием этих значений процентилей для установки пределов x для вывода гистограммы.

Я пробовал кучу исправлений, предложенных в ответах на связанные вопросы, но продолжаю получать разные ошибки, связанные с реактивностью, типом переменной и NA (хотя у меня есть na.rm = TRUE).

Этот пример урезан из более сложного приложения, поэтому я не могу показать все, что я уже пробовал, но я почти уверен, что проблема возникает в команде quantile, и может быть несколько разных проблем с моим кодом. У меня также возникают проблемы с определением процентилей с помощью group_by_, и я не уверен, что успешно учел NSE.

Вот мой файл сервера (проблемы здесь):

  {if (!require("devtools"))
  install.packages("devtools")
  if (!require("ggplot2")) 
    install.packages("ggplot2")
  if (!require("dplyr")) 
    install.packages("dplyr")
  if (!require("lazyeval")) 
    install.packages("lazyeval") }


#load libraries 
library(ggplot2) 
library(dplyr) 
library(lazyeval) 
library(shiny) 

#now the server function
shinyServer(function(input, output) {

  #output for histogram 
  output$histplot <- renderPlot({
    #make objects based on percentiles to trim the histogram you see
    lower.cut <- quantile(as.numeric(input$hist), probs = as.numeric(input$bottom), na.rm = TRUE) #error: missing value where TRUE/FALSE needed
    upper.cut <- quantile(as.numeric(input$hist), probs = as.numeric(input$top), na.rm = TRUE)
    q <- ggplot(iris, aes_string(input$hist)) + geom_histogram(binwidth = (as.numeric(input$n_breaks))) + 
      coord_cartesian(xlim = c(lower.cut, upper.cut)) #I'm not sure whether or not this is working because I can't get past the quantile commands
    q    
  })

  #output for summary stats - among other things, I would like to output the 95th, 98th, and 99th percentile values of the selected histogram variable
  output$summary <- renderPrint({  
  w <- iris %>% group_by_(as.numeric(iris$Species)) %>% summarize_(p95 = quantile(as.numeric(input$hist)), .95, na.rm=TRUE) #error: missing values and NaN's not allowed if 'na.rm' is FALSE
  w 
  })
})

Вот мой файл пользовательского интерфейса (кажется, он работает нормально):

{if (!require("devtools"))
  install.packages("devtools")
  if (!require("ggplot2")) 
    install.packages("ggplot2")
  if (!require("dplyr")) 
    install.packages("dplyr")
  if (!require("lazyeval")) 
    install.packages("lazyeval")
  if (!require("psych")) 
    install.packages("psych") }

library(ggplot2) 
library(dplyr) 
library(lazyeval) 
library(shiny) 

shinyUI(fluidPage(                      
  sidebarPanel( #this stuff will be in the left side panel - all user inputs and notes        
    h3("Histogram"),
    selectInput('hist', 'Histogram Variable', names(iris)), 
    numericInput('n_breaks', 'Histogram Bin Width (type a number, based on axis scale)', value = 10),
    numericInput('bottom', 'Histogram lower limit percentile (type a number between 0 and 1, .01 = exclude bottom 1%)', value = 0), #default no bottom trim
    numericInput('top', 'Histogram upper limit percentile', value = 1), #default no top trim

    hr() 
  ),

  mainPanel( #this stuff will be in the main body of the page - make placeholder spots for the charts
    fluidRow(
      plotOutput("histplot"), #simple histogram

      h4("Summary Statistics for Histogram Variable (grouped by species)"),
      verbatimTextOutput("summary") #output summary statistics below
  ))
))

Вот ошибки, которые я получаю:

Warning in quantile(as.numeric(input$hist), probs = as.numeric(input$bottom),  :
  NAs introduced by coercion
Warning in quantile(as.numeric(input$hist), probs = as.numeric(input$top),  :
  NAs introduced by coercion
Warning: Error in if: missing value where TRUE/FALSE needed
Stack trace (innermost first):
    68: output$histplot
     1: runApp
Warning: Truncating vector to length 1
Warning in quantile(as.numeric(input$hist)) :
  NAs introduced by coercion
Warning: Error in quantile.default: missing values and NaN's not allowed if 'na.rm' is FALSE
Stack trace (innermost first):
    89: quantile.default
    88: quantile
    87: as.lazy_dots
    86: lazyeval::all_dots
    85: summarise_.tbl_df
    84: summarize_
    83: function_list[[k]]
    82: withVisible
    81: freduce
    80: _fseq
    79: eval
    78: eval
    77: withVisible
    76: %>%
    75: renderPrint [R:\Project\EPAR\Working Files\326 - Changes in Yield and Crop Allocation\R analysis\toy_app/server.R#32]
    74: func
    73: eval
    72: eval
    71: withVisible
    70: evalVis
    69: utils::capture.output
    68: paste
    67: output$summary
     1: runApp

Вот вывод sessionInfo():

> sessionInfo()
R version 3.2.4 Revised (2016-03-16 r70336)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252 LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] shinythemes_1.0.1 psych_1.6.6       lazyeval_0.2.0    dplyr_0.5.0       foreign_0.8-66    ggplot2_2.1.0     devtools_1.12.0   shiny_0.13.2     

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.5      magrittr_1.5     mnormt_1.5-4     munsell_0.4.3    colorspace_1.2-6 xtable_1.8-2     R6_2.1.2         stringr_1.0.0    plyr_1.8.4      
[10] tools_3.2.4      parallel_3.2.4   grid_3.2.4       gtable_0.2.0     DBI_0.4-1        withr_1.0.2      htmltools_0.3.5  digest_0.6.9     assertthat_0.1  
[19] tibble_1.0       reshape2_1.4.1   memoise_1.0.0    mime_0.4         labeling_0.3     stringi_1.1.1    scales_0.4.0     jsonlite_0.9.22  httpuv_1.3.3 

person katie.research    schedule 15.07.2016    source источник


Ответы (1)


names(iris) создает вектор символов в вашем скрипте пользовательского интерфейса. Затем ваш серверный скрипт пытается найти квантили путем преобразования этого вектора символов в числовое, что преобразует все ваши имена в NA.

person TClavelle    schedule 15.07.2016
comment
Спасибо за выявление проблемы. Я смог решить это, создав новый объект, а затем вызвав его в выражении квантиля: numvar <- iris[, input$hist] upper.cut <- quantile(numvar, probs = 0.98, na.rm = TRUE) благодаря ответам на этот вопрос: stackoverflow.com/questions/23944590/ - person katie.research; 19.07.2016