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

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

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

    Informations forums :
    Inscription : Février 2020
    Messages : 11
    Points : 6
    Points
    6
    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 du Club
    Homme Profil pro
    Formateur et consultant R
    Inscrit en
    Juin 2020
    Messages
    36
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Paris (Île de France)

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

    Informations forums :
    Inscription : Juin 2020
    Messages : 36
    Points : 69
    Points
    69
    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
    Futur Membre du Club
    Homme Profil pro
    Ingénieur avant-vente
    Inscrit en
    Février 2020
    Messages
    11
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 56
    Localisation : France, Isère (Rhône Alpes)

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

    Informations forums :
    Inscription : Février 2020
    Messages : 11
    Points : 6
    Points
    6
    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 du Club
    Homme Profil pro
    Formateur et consultant R
    Inscrit en
    Juin 2020
    Messages
    36
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Paris (Île de France)

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

    Informations forums :
    Inscription : Juin 2020
    Messages : 36
    Points : 69
    Points
    69
    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
    Futur Membre du Club
    Homme Profil pro
    Ingénieur avant-vente
    Inscrit en
    Février 2020
    Messages
    11
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 56
    Localisation : France, Isère (Rhône Alpes)

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

    Informations forums :
    Inscription : Février 2020
    Messages : 11
    Points : 6
    Points
    6
    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 : 46
    Localisation : France

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

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 064
    Points : 4 478
    Points
    4 478
    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.
    Bon courage.
    Olivier

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

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

    Informations forums :
    Inscription : Février 2020
    Messages : 11
    Points : 6
    Points
    6
    Par défaut
    Merci infiniement de ces precisions qui sont tres claires et m aident a comprendre.
    Bonne journee a vous.

  8. #8
    Membre confirmé
    Inscrit en
    Février 2011
    Messages
    276
    Détails du profil
    Informations forums :
    Inscription : Février 2011
    Messages : 276
    Points : 561
    Points
    561
    Par défaut
    Bonjour,

    Un complément.
    Ce qui ne fonctionne pas forcément dans la console, peut fonctionner dans le corps d'une fonction :
    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
    f1 <- function(x, y) {
      if (y==2)
      {
      x^2
      }
      else if (y==3)
      {
      x^3
      }
      else
      {
      x^y
      }
    }
     
    f1(2, 2)
    f1(2, 3)
    f1(2, 6)
    Quand tu tapes sur une ligne dans la console quelque chose comme x <- mean alors c'est interpréter comme la fonction mean qui est stocké dans l'objet x qui sera donc une fonction. D'où ton problème avec le renderplot. Par contre si tu ouvres la parenthèse tu peux alors très bien mettre l'accolade à la ligne du dessous :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    library(microbenchmark)
    microbenchmark(
    {
    x <- 1:10
    }
    ,
    {
    x <- seq_len(10)
    }
    )
    Après un if sans accolade n'est pas un if qui ne fait rien. On peut le faire s'il n'y a qu'une seule expression qui vient par la suite :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    x <- 2
    y <- 3
    if (y==3) z <- 3 else z <- 4
    # ou encore
    z <- if (y ==3) 3 else 4
    Après ceci ne fonctionne pas parce que l'execution s'arrête à la fin du if, mais il faut faire le distingo entre la console et le coeur des fonctions :
    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
    # ne fonctionne pas complètement
    if (y == 3)
      z <- 3
    else
      z <- 4
    # oui mais ...
    f <- function(x, y) {
      if (y == 3)
        z <- 3
      else
        z <- 4
      z
      }
    f(2, 5)
    [1] 4
    Il y a donc l'interprétation dans la console et ce qui se passe dans les fonctions.
    Tu peux aussi ouvrir un script dans la console qui lui sera parfaitement interprété :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    {
    if (y == 3)
        z <- 3
      else
        z <- 4
    }
    z
    Cordialement

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

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

    Informations forums :
    Inscription : Février 2020
    Messages : 11
    Points : 6
    Points
    6
    Par défaut
    Merci beaucoup Tototode pour ce complement.
    Les choses sont beaucoup plus claire maintenant.

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

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

    Informations forums :
    Inscription : Février 2020
    Messages : 11
    Points : 6
    Points
    6
    Par défaut Subset qui n est pas reactif
    Bonjour a tous,
    mon app shiny fonctionne très bien avec la sélection réactive "Choice" = "n" , "e" ou "s" comme déjà explique ci dessus.

    Je cherche maintenant a rajouter un choix de pays (toujours en réactif).

    Voici le UI:
    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
     
    library(shiny)
     
    # Define UI for application that draws a histogram
    shinyUI(fluidPage(
        verticalLayout( 
            # Application title
            titlePanel("Count of RFE Notes/Emails/SRs per quarter and per Agent"),
     
            # Radio button for the choice
            radioButtons("Choice","Chose between Notes, Emails or SRs:",choices = list("Notes"="n","Emails"="e","SRs"="s")),
     
            # Select input for the country
            selectInput("CountryChoice", "Select the Region or the Country", c=list("Slovenia" = "SLOVEN","Vietnam" = "VIETN","Cyprus" = "CYPRU",
                    "Martinique" = "MARTI","South Africa" = "SAFRI","Qatar" = "QATAR","Lebanon" = "LEBAN","Belgium" = "BELGI","France" = "FRANC",
                    "Norway" = "NORWA","Switzerland" = "SWITZ","Finland" = "FINLA","Monaco" = "MONAC","Russia" = "RUSSI","Sweden" = "SWEDE",
                    "India" = "INDIA","Kuwait" = "KUWAI","Greece" = "GREEC","Austria" = "AUSTR","Pakistan" = "PAKIS","Portugal" = "PORTU",
                    "Romania" = "ROMAN","Spain" = "SPAIN","Israel" = "ISRAE","Luxembourg" = "LUXEM","Netherlands" = "NETHE","Germany"  ="GERMA",
                    "Denmark" = "DENMA","Guadeloupe" = "GUADE","Czech Rep" = "CZECH","Iceland" = "ICELA","Ireland" = "IRELA","Utd Arab Emir" = "EMIRA",
                    "Turkey" = "TURKE","Slovakia" = "SLOVA","Egypt" = "EGYPT","Poland" = "POLAN","Italy" = "ITALY","Saudi Arabia" = "SAUDI",
                    "United Kingdom" = "UKING","Bulgaria" = "BULGA")),
     
            # Show a plot of the generated distribution
            plotOutput("graph")
        )
    )
    )
    Et voici le 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
     
    .......debut du fichier R....
            Choice <- reactive ({Choice <- input$Choice})
            CountryChoice <- reactive ({CountryChoice <- input$CountryChoice})
     
            output$graph <- renderPlot ({
            if (Choice() =="n") {
                CountNotePerAgentdfCountry <- subset (CountNotePerAgentdf, Country=CountryChoice())
                #print (CountryChoice())
                #print (CountNotePerAgentdf)
                #print (CountNotePerAgentdfCountry)
                ggplot (CountNotePerAgentdfCountry, 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 = paste("Number of SHR Notes by Agent and by Quarter for",CountryChoice()), 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"){
    Je n ai mit que la partie nécessaire a la compréhension du problème. Comme déjà explique plus haut le data.frame CountNotePerAgentdf fonctionne très bien. Je ne montre que la partie du If/Else If/Else qui correspond au choix "n" (le problème est le même pour les autres choix).

    Mon problème est le suivant: j arrive a afficher mon radiobutton et mon select input dans le UI, j arrive a selectionner des valeurs mais seule "Choice" provoque un rafraichissement du graphique.
    CountryChoice est bien prit en compte mais ne provoque aucun changement au niveau du graphique (sauf pour le titre (labs (title = paste....) qui prend en compte le changement de pays).

    J ai glisser les 3 print que vous voyez actuellement précédé d un # pour debuguer: CountryChoice est bien rafraîchit mais CountNotePerAgentdf et CountNotePerAgentdfCountry sont identiques ce qui me laisse supposer que
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    CountNotePerAgentdfCountry <- subset (CountNotePerAgentdf, Country=CountryChoice())
    ne fonctionne pas (ou n est pas réactif).

    Comment faire pour rendre mon subset reactif ?
    Merci d avance.

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

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

    Informations forums :
    Inscription : Février 2020
    Messages : 11
    Points : 6
    Points
    6
    Par défaut
    j ai trouve, ca fonctionne avec ceci:
    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
     
            Choice <- reactive ({Choice <- input$Choice})
            CountryChoice <- reactive ({CountryChoice <- input$CountryChoice})
     
            output$graph <- renderPlot ({
            if (Choice() =="n") {
                CountNotePerAgentdfCountry <- reactive ({subset (CountNotePerAgentdf, CountNotePerAgentdf$Country %in% CountryChoice())})
                print (c(CountryChoice()))
                print (CountNotePerAgentdf)
                print (CountNotePerAgentdfCountry())
                ggplot (CountNotePerAgentdfCountry(), 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 = paste("Number of SHR Notes by Agent and by Quarter for",CountryChoice()), 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"){
    Dites moi si ca vous semble acceptable (sachant que ca fonctionne), ou si certaines lignes pourraient etre modifiees.
    Merci a tous.

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