2015-07-26 2 views
1

Я только начинаю знакомство с R и пытаюсь подготовить блестящее приложение. Я только что закончил свой код для ui.R и server.R, но я получаю следующее сообщение об ошибке:RStudio - Shiny - Error «Операция не разрешена без активного реактивного контекста»

Error in unique.default(x, nmax = nmax) : unique() applies only to vectors

Это мои ui.R и server.R файлы:

ui.r

shinyUI(pageWithSidebar(
    headerPanel("Cosmo Test"), 
    sidebarPanel(
    radioButtons(inputId="Dest", label="1. Favorite Holidays Destination:", selected=NULL, 
       choices=c("Rome" = 1, "New York" = 2, "Gaborone" = 3, "Arctic Pole" = 4)), 
    radioButtons(inputId="Food", label="2. Favorite Food/Meal:", selected=NULL, 
       choices=c("Strawberry Pie" = 1, "Fish & Chips" = 2, "Snake B-B-Q" = 3, "sashimi" = 4)), 
    radioButtons(inputId="Clothing", label="Favorite Clothing Style:", selected=NULL, 
       choices=c("Comfy" = 1, "Stylish" = 2, "Practical" = 3, "Clothing?" = 4)), 
    submitButton("Submit") 
), 

    mainPanel(
    h3("Cosmo Results"), 
    h4("Based on your answers, you are a..."), 
    verbatimTextOutput("Result1"), 
    verbatimTextOutput("ResultExplained") 
) 

)) 

сервер .R

shinyServer(
    function(input,output) { 
    Type<-reactive({ 
     as.vector(c(input$Dest,input$Food,input$Clothing)) 
    }) 
    frec.var<-(table(Type)) 
     valor<-which(frec.var==max(frec.var)) # Elementos con el valor m´aximo 
     my_mode<-as.vector(valor) 

    output$Result1<-renderText({ 
     if(my_mode(Type)=="1") "Romantic" 
     else if (my_mode(Type)=="2") "Hypster" 
     else if (my_mode(Type)=="3") "Penguin" 
     else "Undefined" 
    }) 
    output$ResultExplained<-renderText({ 
     if(my_mode(Type)=="1") "Love is all around you... and you love it!!" 
     else if (my_mode(Type)=="2") "Grab your electric bike, your reflex cam and go make the world a fancier place" 
     else if (my_mode(Type)=="3") "How exactly were you able fill this test???" 
     else "You're too complex to be a Cosmo reader; are you sure you picked the right magazine?" 
    }) 
    }) 

Целью является получение результата на основе режима ответов первой части (1,2,3 или 4). Я рассмотрел как десяток записей о уникальных() проблемах, но не смог найти ничего, что помогло бы мне решить проблему.

Может ли кто-нибудь взглянуть на мой код? Я предполагаю, что это должно быть что-то глупое, но я не могу найти его, ни обходного пути, чтобы избежать текущего кода server.R, который работает.

С наилучшими пожеланиями, Игнасио

ответ

1

Прежде всего Type является реактивным переменным это означает, что он должен быть вызван (Type()) для доступа к значению, кроме того, она может быть доступна только в реактивном контексте (reactive, observe , render*, isolate).

После некоторого переписывания:

library(shiny) 

shinyServer(function(input,output) { 
    Type <- reactive({ 
     tab <- table(c(input$Dest,input$Food,input$Clothing)) 
     names(tab)[which.max(tab)] 
    }) 


    output$Result1<-renderText({ 
     default <- "Undefined" 
     r <- list("1" = "Romantic", "2" = "Hypster", "3"="Penguin")[[Type()]] 
     ifelse(is.null(r), default, r) 
    }) 

    output$ResultExplained<-renderText({ 
     default <- paste(
      "You're too complex to be a Cosmo reader;", 
      "are you sure you picked the right magazine?" 
     ) 
     r <- list(
      "1" = "Love is all around you... and you love it!!", 
      "2" = paste(
       "Grab your electric bike, your reflex", 
       "cam and go make the world a fancier place" 
      ), 
      "3" = "How exactly were you able fill this test???" 
     )[[Type()]] 
     ifelse(is.null(r), default, r) 
    }) 
}) 
+0

спасибо! Я пробовал как тысячу решений, .. – Ignacio1981

Смежные вопросы