IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

R Discussion :

Message d erreur sous Rshiny


Sujet :

R

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre habitué
    Homme Profil pro
    Ingénieur avant-vente
    Inscrit en
    Février 2020
    Messages
    11
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 57
    Localisation : France, Isère (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur avant-vente
    Secteur : Santé

    Informations forums :
    Inscription : Février 2020
    Messages : 11
    Par défaut Message d erreur sous Rshiny
    Bonjour a tous
    je debute sous Rshiny et ma premiere app ne se passe pas comme il faut.

    j ai cree un fichier sous RStudio qui fonctionne correctement. J aimerais utiliser RShiny pour donner la possibilite de choisir entre 3 graphique differents (representant 3 valeures issue du fichier R).

    Le fichier R n est pas montre dans le programme ci joint mais sachez que ca fonctionne correctement et que j arrive a afficher les 3 graphiques (un a un).

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
     
    library(shiny)
     
    # Define UI for application that draws a histogram
    shinyUI <-(fluidPage(
     
        # Application title
        titlePanel("Count of RFE Note/Email/SR per quarter and per Agent"),
        sidebarLayout(
                sidebarPanel(
                    # Radio button for the choice
                    radioButtons("Choice","Your choice:",choices = list("Note"="n","Email"="e","SR"="s"))
                            ),
     
                # Show a plot of the generated distribution
                mainPanel(
                    plotOutput("graph")
                        )
                    )
    ))
    et voici la partie Server
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
     
    library(shiny)
     
    # Define server logic required to draw a histogram
    shinyServer <-
    (function(input, output) 
    {
     
    --- ici intervient mon fichier R qui fonctionne correctement----
     
          output$graph <- renderPlot 
          ({ 
            Choice <- reactive({rexp(input$Choice)})
            if (as_tibble(Choice()) == "n")
            { 
              ggplot (CountNotePerAgentdf, aes(x=YandQ, y=Count))+
              geom_bar(stat="identity",position="dodge",fill='#3333FF', width =.4 )+ # identity means that both x and y values are from the dataframe
              facet_grid(.~ Agent)+
              labs (title = "Number of SHR Note by Agent and by Quarter", x = "Year and Quarter", y = "Count of SHR Note")+ # to show the title
              theme(axis.text.x = element_text(angle=45)) # to incline the labels at 45 degrees 
            }  
            if (as_tibble(Choice()) == "e")
            {
              ggplot (CountEmailPerAgentdf, aes(x=YandQ, y=Count))+
              geom_bar(stat="identity",position="dodge",fill='#3333FF', width =.4 )+ # identity means that both x and y values are from the dataframe
              facet_grid(.~ Agent)+
              labs (title = "Number of SHR Email by Agent and by Quarter", x = "Year and Quarter", y = "Count of SHR Email")+ # to show the title
              theme(axis.text.x = element_text(angle=45)) # to incline the labels at 45 degrees  
            }
            if (as_tibble(Choice())== "s")
            {
              ggplot (CountSRPerAgentdf, aes(x=YandQ, y=Count))+
              geom_bar(stat="identity",position="dodge",fill='#3333FF', width =.4 )+ # identity means that both x and y values are from the dataframe
              facet_grid(.~ Agent)+
              labs (title = "Number of SHR SR by Agent and by Quarter", x = "Year and Quarter", y = "Count of SHR SR")+ # to show the title
              theme(axis.text.x = element_text(angle=45)) # to incline the labels at 45 degrees 
            }
     
          })
    Mon radio button s affiche correctement mais disparait au bout de qq secondes et j ai le message suivant:

    Error in .getReactiveEnvironment()$currentContext() :
    Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
    Warning: Error in exprToFunction: argument "expr" is missing, with no default


    Je comprend que ma variable Input n est pas reactive mais je ne sait pas quoi faire.
    Votre aide serait precieuse...
    Merci a tous

  2. #2
    Membre éclairé
    Homme Profil pro
    Formateur et consultant R
    Inscrit en
    Juin 2020
    Messages
    36
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Formateur et consultant R
    Secteur : Conseil

    Informations forums :
    Inscription : Juin 2020
    Messages : 36
    Par défaut
    Bonjour,

    Par construction, ce qu'il y a dans "input" est réactif. Il n'est donc pas nécessaire de le remettre dans une reactive.
    Par ailleurs, vous pouvez utiliser "else if" pour éviter de tester toutes les conditions si une est bonne avant.
    En théorie, votre code devrait fonctionner de cette manière :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
     
    library(shiny)
     
    # Define server logic required to draw a histogram
    shinyServer <-
    (function(input, output) 
    {
     
    --- ici intervient mon fichier R qui fonctionne correctement----
     
          output$graph <- renderPlot 
          ({ 
            Choice <- input$Choice
            if (Choice == "n")
            { 
              ggplot (CountNotePerAgentdf, aes(x=YandQ, y=Count))+
              geom_bar(stat="identity",position="dodge",fill='#3333FF', width =.4 )+ # identity means that both x and y values are from the dataframe
              facet_grid(.~ Agent)+
              labs (title = "Number of SHR Note by Agent and by Quarter", x = "Year and Quarter", y = "Count of SHR Note")+ # to show the title
              theme(axis.text.x = element_text(angle=45)) # to incline the labels at 45 degrees 
            }  else if (Choice == "e")   {
              ggplot (CountEmailPerAgentdf, aes(x=YandQ, y=Count))+
              geom_bar(stat="identity",position="dodge",fill='#3333FF', width =.4 )+ # identity means that both x and y values are from the dataframe
              facet_grid(.~ Agent)+
              labs (title = "Number of SHR Email by Agent and by Quarter", x = "Year and Quarter", y = "Count of SHR Email")+ # to show the title
              theme(axis.text.x = element_text(angle=45)) # to incline the labels at 45 degrees  
            } else if (Choice == "s")   {
              ggplot (CountSRPerAgentdf, aes(x=YandQ, y=Count))+
              geom_bar(stat="identity",position="dodge",fill='#3333FF', width =.4 )+ # identity means that both x and y values are from the dataframe
              facet_grid(.~ Agent)+
              labs (title = "Number of SHR SR by Agent and by Quarter", x = "Year and Quarter", y = "Count of SHR SR")+ # to show the title
              theme(axis.text.x = element_text(angle=45)) # to incline the labels at 45 degrees 
            }
     
          })

  3. #3
    Membre habitué
    Homme Profil pro
    Ingénieur avant-vente
    Inscrit en
    Février 2020
    Messages
    11
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 57
    Localisation : France, Isère (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur avant-vente
    Secteur : Santé

    Informations forums :
    Inscription : Février 2020
    Messages : 11
    Par défaut message d erreur sous R Shiny
    Merci de votre aide mais ca ne fonctionne toujours pas.

    J ai modifie mon code sous RStudio comme ci dessous. J ai volontairement creer une variable a laquelle je donne la valeur "n" ou "e" ou "s", mon test if/else if/else fonctionne et affiche bien le graphique correspondant:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
     
    Choice <- "s"
     
    if (Choice =="n") {
        ggplot (CountNotePerAgentdf, aes(x=YandQ, y=Count))+
        geom_bar(stat="identity",position="dodge",fill='#3333FF', width =.4 )+ # identity means that both x and y values are from the dataframe
        facet_grid(.~ Agent)+
        labs (title = "Number of SHR Note by Agent and by Quarter", x = "Year and Quarter", y = "Count of SHR Note")+ # to show the title
        theme(axis.text.x = element_text(angle=45)) # to incline the labels at 45 degrees 
    }else if (Choice =="e"){
        ggplot (CountEmailPerAgentdf, aes(x=YandQ, y=Count))+
        geom_bar(stat="identity",position="dodge",fill='#3333FF', width =.4 )+ # identity means that both x and y values are from the dataframe
        facet_grid(.~ Agent)+
        labs (title = "Number of SHR Email by Agent and by Quarter", x = "Year and Quarter", y = "Count of SHR Email")+ # to show the title
        theme(axis.text.x = element_text(angle=45)) # to incline the labels at 45 degrees 
    }else {
        ggplot (CountSRPerAgentdf, aes(x=YandQ, y=Count))+
        geom_bar(stat="identity",position="dodge",fill='#3333FF', width =.4 )+ # identity means that both x and y values are from the dataframe
        facet_grid(.~ Agent)+
        labs (title = "Number of SHR SR by Agent and by Quarter", x = "Year and Quarter", y = "Count of SHR SR")+ # to show the title
        theme(axis.text.x = element_text(angle=45)) # to incline the labels at 45 degrees 
    }

    Voici mon code sous Shiny (j ai bien sur supprime la variable: Choice <- "s" )
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
     
           output$graph <- renderPlot 
            ({ 
                Choice <- input$Choice
     
                if (Choice =="n") {
                  ggplot (CountNotePerAgentdf, aes(x=YandQ, y=Count))+
                    geom_bar(stat="identity",position="dodge",fill='#3333FF', width =.4 )+ # identity means that both x and y values are from the dataframe
                    facet_grid(.~ Agent)+
                    labs (title = "Number of SHR Note by Agent and by Quarter", x = "Year and Quarter", y = "Count of SHR Note")+ # to show the title
                    theme(axis.text.x = element_text(angle=45)) # to incline the labels at 45 degrees 
                }else if (Choice =="e") {
                  ggplot (CountEmailPerAgentdf, aes(x=YandQ, y=Count))+
                    geom_bar(stat="identity",position="dodge",fill='#3333FF', width =.4 )+ # identity means that both x and y values are from the dataframe
                    facet_grid(.~ Agent)+
                    labs (title = "Number of SHR Email by Agent and by Quarter", x = "Year and Quarter", y = "Count of SHR Email")+ # to show the title
                    theme(axis.text.x = element_text(angle=45)) # to incline the labels at 45 degrees 
                }else if (Choice=="s") {
                  ggplot (CountSRPerAgentdf, aes(x=YandQ, y=Count))+
                    geom_bar(stat="identity",position="dodge",fill='#3333FF', width =.4 )+ # identity means that both x and y values are from the dataframe
                    facet_grid(.~ Agent)+
                    labs (title = "Number of SHR SR by Agent and by Quarter", x = "Year and Quarter", y = "Count of SHR SR")+ # to show the title
                    theme(axis.text.x = element_text(angle=45)) # to incline the labels at 45 degrees 
                }
     
            })
    Neanmoins lorsque je test le code sous Shiny, j obtiens toujours la meme erreur:

    Listening on http://127.0.0.1:6172
    Warning: Error in .getReactiveEnvironment()$currentContext: Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
    58: stop
    57: .getReactiveEnvironment()$currentContext
    56: getCurrentContext
    52: .subset2(x, "impl")$get
    51: $.reactivevalues
    49: server [/home/INTSURG/marcch/Note_Email_SR/server.R#110]
    Error in .getReactiveEnvironment()$currentContext() :
    Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
    Warning: Error in exprToFunction: argument "expr" is missing, with no default
    85: eval
    84: makeFunction
    83: exprToFunction
    82: installExprFunction
    81: output$graph
    1: runApp


    Mon radiobutton s affiche pendant 2 ou 3 seconds mais disparait pour laisser place au message d erreur ci dessus.
    Je ne vois pas d ou viens le probleme….
    Merci d avance.

  4. #4
    Membre éclairé
    Homme Profil pro
    Formateur et consultant R
    Inscrit en
    Juin 2020
    Messages
    36
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Formateur et consultant R
    Secteur : Conseil

    Informations forums :
    Inscription : Juin 2020
    Messages : 36
    Par défaut
    Bonjour,

    Je ne pense pas que le problème vienne du bouton.
    Je ne peux pas reproduire votre app car je n'ai pas accès aux données "CountNotePerAgentdf". D'ailleurs, je me demande le format de cette variable. Si c'est une reactive, il faudrait l'appeler avec "CountNotePerAgentdf()".
    Ceci dit, pour déboguer votre code, vous pouvez insérer un "browser()" juste avant le "Choice".
    De cette manière, vous pourrez regarder le format des objets dans la console R directement en mode débogage.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
     output$graph <- renderPlot 
            ({ 
                Choice <- input$Choice
     
               browser() # Pensez à commenter cette ligne quand vous avez trouvé la source de vos problèmes.
     
                if (Choice =="n") {
                  ggplot (CountNotePerAgentdf, aes(x=YandQ, y=Count))+
                    geom_bar(stat="identity",position="dodge",fill='#3333FF', width =.4 )+ # identity means that both x and y values are from the dataframe
                    facet_grid(.~ Agent)+
                    labs (title = "Number of SHR Note by Agent and by Quarter", x = "Year and Quarter", y = "Count of SHR Note")+ # to show the title
                    theme(axis.text.x = element_text(angle=45)) # to incline the labels at 45 degrees 
                }else if (Choice =="e") {
                  ggplot (CountEmailPerAgentdf, aes(x=YandQ, y=Count))+
                    geom_bar(stat="identity",position="dodge",fill='#3333FF', width =.4 )+ # identity means that both x and y values are from the dataframe
                    facet_grid(.~ Agent)+
                    labs (title = "Number of SHR Email by Agent and by Quarter", x = "Year and Quarter", y = "Count of SHR Email")+ # to show the title
                    theme(axis.text.x = element_text(angle=45)) # to incline the labels at 45 degrees 
                }else if (Choice=="s") {
                  ggplot (CountSRPerAgentdf, aes(x=YandQ, y=Count))+
                    geom_bar(stat="identity",position="dodge",fill='#3333FF', width =.4 )+ # identity means that both x and y values are from the dataframe
                    facet_grid(.~ Agent)+
                    labs (title = "Number of SHR SR by Agent and by Quarter", x = "Year and Quarter", y = "Count of SHR SR")+ # to show the title
                    theme(axis.text.x = element_text(angle=45)) # to incline the labels at 45 degrees 
                }
     
            })

  5. #5
    Membre habitué
    Homme Profil pro
    Ingénieur avant-vente
    Inscrit en
    Février 2020
    Messages
    11
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 57
    Localisation : France, Isère (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur avant-vente
    Secteur : Santé

    Informations forums :
    Inscription : Février 2020
    Messages : 11
    Par défaut suite et fin
    Merci de votre aide. J ai trouve la solution:

    Il faut bel et bien utiliser une fonction reactive:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    Choice <- reactive ({Choice <- input$Choice})
    Choice <- input$Choice ne suffit pas.

    De plus (je suis assez surprit que R soit si "sensible" au retour a la ligne) , ceci ne fonctionne pas:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
            output$graph <- renderPlot 
            ({
    il faut que les ({ soit sur la meme ligne, comme ceci:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    output$graph <- renderPlot ({

    J ai constate la meme "sensibilite" pour la fonction IF/ELSE IF :
    ceci ne fonctionne pas
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
                if (Choice() =="n") 
                  {
    alors que ceci fonctionne:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    if (Choice() =="n") {
    Le language PHP que je pratiquais avant etait moins sensible....

    Merci en tout ca de votre aide.

  6. #6
    Expert confirmé
    Avatar de olivier.decourt
    Homme Profil pro
    Formateur R/SAS/statistiques
    Inscrit en
    Avril 2008
    Messages
    2 064
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : France

    Informations professionnelles :
    Activité : Formateur R/SAS/statistiques
    Secteur : Conseil

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 064
    Par défaut
    Bonjour.
    Ce n'est pas exactement une "sensibilité" au retour à la ligne mais plutôt l'interprétation faite d'un langage qui a quelques délimiteurs explicites mais aucun qui soit systématique.
    Dans R, arrivé à la fin d'une ligne, la question est "est-ce que ce code est terminé ? dois-je l'exécuter ?". Un exemple classique est
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    2+2 # réponse -> 4
    2+
    2 # réponse --> 4 puisqu'en fin de ligne précédente, le calcul n'est clairement pas fini
    2
    +2 # réponses --> 2 et 2 puisqu'en fin de ligne précédente, rien n'indique que le calcul continue
    Le souci est le même avec les accolades qui suivent les if, les for et autres structures de contrôle. Si on ne les laisse pas ouvertes en fin de ligne, R pense que la structure de contrôle est terminée parce qu'on peut vouloir faire un if sans accolades (un if qui ne fait rien) : c'est une syntaxe licite. Dans d'autres langages on devrait indiquer une ponctuation de manière systématique pour délimiter l'action liée au if.
    Autre cas récurrent où le problème survient, les enchaînements type {magrittr}/{dplyr} où il faut laisser un %>% en fin de ligne pour réussir à enchaîner correctement la ligne suivante.

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo