Problema ao rodar Shiny no "Run App"

Olá pessoal. Estou tentando rodar meu App no Shiny usando o pacote ShinyDashboard.

Um primeiro problema estranho é que ao rodar este código da UI abaixo (uso Ctrl+Enter), e ele vai até o penúltimo parênteses e não armazena o objeto. É estranho pois eu já chequei detalhadamente e acho que o número de “parênteses” está correto. Se eu selecionar todas as linhas do código da UI e apertar Ctrl+Enter ele consegue armazenar o objeto.

library(shiny)
library(shinydashboard)
#> 
#> Attaching package: 'shinydashboard'
#> The following object is masked from 'package:graphics':
#> 
#>     box
library(tidyverse)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union

df <- readr::read_csv("data/dados_sisab.csv")
#> Error: 'data/dados_sisab.csv' does not exist in current working directory ('C:/Users/rafae/AppData/Local/Temp/RtmpSYJCHv/reprex-24e4722d6f98-sour-puppy').

ui <- dashboardPage(
  dashboardHeader(title = "Monitoramento da APS - Dias d'Ávila (Ba)",
                  titleWidth = 600
                  ),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Sobre a pesquisa", tabName = "about"),
      menuItem("Atendimento Individual", tabName = "atend_ind",
      menuSubItem("Médico(a)", tabName = "atend_med"),
      menuSubItem("Enfermeiro(a)", tabName = "atend_enf"),
      menuSubItem("Cirurgião Dentista", tabName = "atend_odonto")),
      menuItem("Cobertura por equipe", tabName = "cob_por_equipe")
    )
  ),
  dashboardBody(
    tabItems(
      tabItem("about",
              h3("Avaliação da implantação do Prontuário Eletrônico do Cidadão (PEC) na rede de atenção à saúde em Dias d'Ávila (BA)"),
              p(HTML("Este relatório é produto do <b>Sub-projeto 2 'Avaliação da implantação do prontuário eletrônico do cidadão (PEC) 
                     na rede de atenção à saúde de Dias d'ávila (BA)'</b>, que integra o projeto maior intitulado 'Relação entre iniquidades 
                     e inovação em saúde: foco em Qualidade-Equidade e Competência Tecnológica Crítica no SUS' financiado pelo Ministério 
                     da Saúde  através da Chamada MS-SCTIE-Decit/CNPq nº 12/2018 – Pesquisas de inovação em saúde"))
              ),
      tabItem(
        "atend_med",
        mod_atend_med_UI("atend_med")
        ),
      tabItem(
        "atend_enf"
      )
    )
  )
)
#> Error in mod_atend_med_UI("atend_med"): não foi possível encontrar a função "mod_atend_med_UI"


server <- function(input, output, session) {
  
  mod_atend_med_server("atend_med", df)
  
}

shinyApp(ui, server)
#> Error in force(ui): objeto 'ui' não encontrado

Created on 2021-09-30 by the reprex package (v2.0.1)

Outro problema é que, quando eu tento fazer o deployApp() para publicar o App no Shiny IO dá o seguinte erro:

Attaching package: ‘shinydashboard’

The following object is masked from ‘package:graphics’:

box

── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
:heavy_check_mark: ggplot2 3.3.5 :heavy_check_mark: purrr 0.3.4
:heavy_check_mark: tibble 3.1.4 :heavy_check_mark: dplyr 1.0.7
:heavy_check_mark: tidyr 1.1.4 :heavy_check_mark: stringr 1.4.0
:heavy_check_mark: readr 2.0.2 :heavy_check_mark: forcats 0.5.1
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
:heavy_multiplication_x: dplyr::filter() masks stats::filter()
:heavy_multiplication_x: dplyr::lag() masks stats::lag()

Attaching package: ‘lubridate’

The following objects are masked from ‘package:base’:

date, intersect, setdiff, union

Rows: 4476 Columns: 12
── Column specification ────────────────────────────────────────────────────────
Delimiter: “,”
chr (7): Uf, Municipio, comp, cat_prof, tipo_prod, nome_equipe, tp_equipe
dbl (4): cod_ine, cod_cnes, cod_ibge, valor_produzido
date (1): date

:information_source: Use spec() to retrieve the full column specification for this data.
:information_source: Specify the column types or set show_col_types = FALSE to quiet this message.
Error in value[3L] :
objeto de tipo ‘closure’ não possível dividir em subconjuntos
Calls: local … tryCatch → tryCatchList → tryCatchOne →
Execução interrompida

Não faço ideia de onde exatamente está o erro. Mas o App roda na minha máquina quando eu aperto o botão Run App. Aliás, sobre isso, ele só roda quando eu abro o arquivo do módulo e carrego o objeto da função “mod_atend_med_UI” e “mod_atend_med_server”. E em seguida carrego os objetos com a UI e server no arquivo principal (app.R).

O código do modulo que eu uso é o seguinte:

mod_atend_med_UI <- function(id) {
  
   ns <- NS(id)
  tagList(
    h3("Atendimentos individuais de médicos"),
    fluidRow(
      column(
        width = 2,
        dateRangeInput(
          ns("time"), 
          label = "Período",
          start = max(df$date) - years(1),
          end = max(df$date),
          min = min(df$date), 
          max = max(df$date),
          separator = " a ",
          format = "M/yyyy"
        )
      ),
      column(
        width = 10,
        imageOutput(ns("grafico"),
                   width = "100%",
                   height = 1200)
      )
    )
  )
}

mod_atend_med_server <- function(id, df) {
  shiny::moduleServer(
    id,
    function(input, output, session) {
      output$grafico <- renderImage({
          # A temp file to save the output.
        Plot <- df %>%
          filter(cat_prof == "Médico") %>% 
          filter(date >= input$time[1] & date <= input$time[2]) %>%
          ggplot() + {
            if (input$time[2] - input$time[1] <= months(12)) {
              geom_line(aes( x = date, y = valor_produzido), color = "#266EFE", size = 1.5)
            } else {
              geom_line(aes( x = date, y = valor_produzido), color = "#266EFE", size = 1) }
            } + {
          if (input$time[2] - input$time[1] <= months(12)) {
            geom_label(aes(x = date, y = valor_produzido, label = valor_produzido), size = 3,
                           label.padding = unit(0.10, "lines"))
          } else {
            geom_label(aes(x = date, y = valor_produzido, label = valor_produzido), size = 2,
                           label.padding = unit(0.10, "lines")) }
      } +
          facet_wrap(vars(nome_equipe))+
          labs(
            x = "Mês/Ano",
            y = "Nº de atendimentos",
            caption = "Fonte: SISAB/MS"
          )+ {
          if (input$time[2] - input$time[1] <= months(12)) {
            scale_x_date(date_labels = "%b\n%Y", date_breaks = "2 months")
            } else { 
              scale_x_date(date_labels = "%b\n%Y", date_breaks = paste0(as.double((input$time[2] - input$time[1]))/60," months")) }
            } +
              theme_bw()+
              theme(plot.title = element_text(size = 9, face = "bold"),
                    panel.background = element_rect(fill = 'white'),
                    axis.text.x = element_text(size = 9),
                    strip.text = element_text(size= 12))

          # This file will be removed later by renderImage
          outfile <- tempfile(fileext = '.png')
          
          # Generate the PNG
          png(outfile, 
              width = 1080*4, 
              height = 1200*4,
              res = 96*4)
          print(Plot)
          dev.off()
          
          # Return a list containing the filename
          list(src = outfile,
               contentType = 'image/png',
               width = 1080,
               height = 1200,
               alt = "This is alternate text")
        }, deleteFile = TRUE)
      })
        }

Created on 2021-09-30 by the reprex package (v2.0.1)

Olá pessoal. Já resolvi o problema. Em tese, eu carreguei o banco de dados em cada um dos meus módulos. Não sei se realmente isso é necessário mas resolveu meu problema.

Em relação ao problema com os parênteses, tenho evitado rodar o App selecionando tudo e apertando Ctrl + Enter e sim apertando o botão Run App após limpar o enviroment e carregando nova seção do R.