Introdução

A programação foi desenvolvida na linguagem e ambiente de Computação Estatística R (Orientada a objeto, semelhante ao Python). Pode ser baixada gratuitamente em https://www.r-project.org/; IDE RStudio (IDE RStudio).

Visa ajudar na conferência dos militares e dias trabalhados após confecção no excel. Encontra-se em construção! .

Para instruções de instalação do R e RStudio, consulte os links:

  1. https://lhmet.github.io/adar-ebook/install.html (para linux ubuntu);

  2. https://livro.curso-r.com/1-1-instala%C3%A7%C3%A3o-do-r.html (Windows ou linux).

Objetivo

  1. Criar uma funcão para extração dos dias trabalhados;

  2. Preencher as planilhas de Etapas com os dias extraídos.

Svç. Dupla ou 1 por T

Função Extratora 2

extracao_etapas2<-function(dd){ 
              
   cod<-c("C","R","V","S","A","I","L","D","T","N","O") # Identificacao
                  
   n<-length(cod); Info<-list()
                        
      for (i in 1:n){
         
         svc<-which(dd==cod[i],arr.ind = TRUE)[,1] #Matriz de indice(Todos os svçs)
         
         svc_12h<-sort(svc[!svc %in% svc[duplicated(svc)]]) #Extracao de nao duplicados e ord.
         
         svc_24h<-sort(svc[duplicated(svc)]) #Extracao de elementos duplicados e ord.
         
         Info[[i]]<-list(Militar=cod[i],Servico_12h=svc_12h,Servico_24h=svc_24h)
      }
 return(Info)
}

Leitura de dados 2

#-------------------------- NOVEMBRO ------------------------------------------------------------#
setwd("C:\\Users\\adolfoamds\\Documents")

getwd()
## [1] "C:/Users/adolfoamds/Documents"
#install.packages("readxl")
library(readxl)

# Escolher a planilha de novembro
cumprida<-read_excel(file.choose(),sheet = "Cumprida",col_names=TRUE,skip=15)[,c(3,4,6,7)] 


#--------------------------- TODOS OS MESES -----------------------------------------------------#

Cumprida<-list()

escala<-c("Escala_2020.01.xlsx","Escala_2020.02.xlsx","Escala_2020.03.xlsx","Escala_2020.04.xlsx",
          "Escala_2020.05.xlsx","Escala_2020.06.xlsx","Escala_2020.07.xlsx","Escala_2020.08.xlsx",
          "Escala_2020.09.xlsx","Escala_2020.10.xlsx","Escala_2020.11.xlsx","Escala_2020.12.xlsx")

for (i in 1:12){
      Cumprida[[i]]<-read_excel(escala[i],sheet = "Cumprida",col_names=TRUE,skip=15)[,c(3,4,6,7)]
}

Exemplo de Aplicação 2

Aplicação na escala de novembro de 2020.

Aqui, a função é geral. Serve tanto para serviços em dupla, quanto para o caso de um militar por turno.

# Mostraremos somente as 4 (quatro) primeiras saídas para exemplo:
head(extracao_etapas2(cumprida),4)
## [[1]]
## [[1]]$Militar
## [1] "C"
## 
## [[1]]$Servico_12h
## [1]  4 10 12 17 19 25
## 
## [[1]]$Servico_24h
## [1]  6 22
## 
## 
## [[2]]
## [[2]]$Militar
## [1] "R"
## 
## [[2]]$Servico_12h
## [1] 11 19 24 26
## 
## [[2]]$Servico_24h
## [1]  8 13
## 
## 
## [[3]]
## [[3]]$Militar
## [1] "V"
## 
## [[3]]$Servico_12h
## [1]  2 11 18 20 24 30
## 
## [[3]]$Servico_24h
## [1] 15 28
## 
## 
## [[4]]
## [[4]]$Militar
## [1] "S"
## 
## [[4]]$Servico_12h
## [1]  3  4 10 16 20 23 26 30
## 
## [[4]]$Servico_24h
## [1] 7

Exemplo: Serviços 12 horas

      datatable(extracao_dias(12),extensions = 'Buttons',
                         options = list(dom='Blfrtip',
                                 buttons=c('copy','csv','excel','pdf','print'),
                                 lengthMenu=list(c(-1,5,7,9),c('Todas',5,7,9))),
                         caption = "Dias de Serviços em novembro de 2020")

Exemplo 2: Servicos 24h

datatable(extracao_dias(24),extensions = 'Buttons',
                       options = list(dom='Blfrtip',
                                 buttons=c('copy','csv','excel','pdf','print'),
                                 lengthMenu=list(c(-1,5,7,9),c('Todas',5,7,9))),
                       caption = "Dias de Serviços em novembro de 2020")

Resumo das variáveis 2

# Informacao das variaveis
str(extracao_etapas2(cumprida))
## List of 11
##  $ :List of 3
##   ..$ Militar    : chr "C"
##   ..$ Servico_12h: int [1:6] 4 10 12 17 19 25
##   ..$ Servico_24h: int [1:2] 6 22
##  $ :List of 3
##   ..$ Militar    : chr "R"
##   ..$ Servico_12h: int [1:4] 11 19 24 26
##   ..$ Servico_24h: int [1:2] 8 13
##  $ :List of 3
##   ..$ Militar    : chr "V"
##   ..$ Servico_12h: int [1:6] 2 11 18 20 24 30
##   ..$ Servico_24h: int [1:2] 15 28
##  $ :List of 3
##   ..$ Militar    : chr "S"
##   ..$ Servico_12h: int [1:8] 3 4 10 16 20 23 26 30
##   ..$ Servico_24h: int 7
##  $ :List of 3
##   ..$ Militar    : chr "A"
##   ..$ Servico_12h: int [1:6] 3 5 9 12 16 18
##   ..$ Servico_24h: int [1:2] 1 29
##  $ :List of 3
##   ..$ Militar    : chr "I"
##   ..$ Servico_12h: int [1:5] 17 19 23 25 27
##   ..$ Servico_24h: int(0) 
##  $ :List of 3
##   ..$ Militar    : chr "L"
##   ..$ Servico_12h: int 17
##   ..$ Servico_24h: int [1:2] 21 27
##  $ :List of 3
##   ..$ Militar    : chr "D"
##   ..$ Servico_12h: int [1:3] 2 5 9
##   ..$ Servico_24h: int 14
##  $ :List of 3
##   ..$ Militar    : chr "T"
##   ..$ Servico_12h: int(0) 
##   ..$ Servico_24h: int(0) 
##  $ :List of 3
##   ..$ Militar    : chr "N"
##   ..$ Servico_12h: int [1:5] 2 4 6 10 12
##   ..$ Servico_24h: int(0) 
##  $ :List of 3
##   ..$ Militar    : chr "O"
##   ..$ Servico_12h: int(0) 
##   ..$ Servico_24h: int(0)

Função Extratora 3

Inclusão da leitura na própria função.

extracao_etapas3<-function(nome_arquivo_com_extensao){ 

  dd<-read_excel(nome_arquivo_com_extensao,sheet = "Cumprida",col_names=TRUE,skip=15)[,c(3,4,6,7)]
                  
  n<-length(cod); Info<-list()
                        
      for (i in seq_len(n)){
         
         svc<-which(dd==cod[i],arr.ind = TRUE)[,1] #Matriz de indice(Todos os svçs)
         
         svc_12h<-sort(svc[!svc %in% svc[duplicated(svc)]]) #Extracao de nao duplicados e ord.
         
         svc_24h<-sort(svc[duplicated(svc)]) #Extracao de elementos duplicados e ord.
         
         Info[[i]]<-list(Militar=cod[i],Servico_12h=svc_12h,Servico_24h=svc_24h)
      }
 return(Info)
}

Exemplo de Aplicação 3

Aplicação na escala de janeiro do ano de 2021.

#install.packages("readxl") 
                            
library(readxl)

setwd("C:\\Users\\adolfoamds\\Documents")  #--------------Informe o local do arquivo (Planilha).

cod<-c("C","R","V","S","A","I","L","D","T","N","O") #-----Informe a Identificacao dos militares.

# extracao_etapas3("Escala_2021.01.xlsx")    #--------------Importante: o Nome deve ser entre aspas.

head(extracao_etapas3("Escala_2021.01.xlsx"),4) # mostrando em tela só 4 saídas
## [[1]]
## [[1]]$Militar
## [1] "C"
## 
## [[1]]$Servico_12h
## [1]  1  2  3  5  6 14
## 
## [[1]]$Servico_24h
## [1]  9 17
## 
## 
## [[2]]
## [[2]]$Militar
## [1] "R"
## 
## [[2]]$Servico_12h
## [1] 18 20 23 25 28
## 
## [[2]]$Servico_24h
## integer(0)
## 
## 
## [[3]]
## [[3]]$Militar
## [1] "V"
## 
## [[3]]$Servico_12h
## [1]  5  7 23 26 28
## 
## [[3]]$Servico_24h
## [1] 30
## 
## 
## [[4]]
## [[4]]$Militar
## [1] "S"
## 
## [[4]]$Servico_12h
## [1]  4  6 12 14 18 27
## 
## [[4]]$Servico_24h
## [1]  8 16

Tabela e Gráficos

############# REVISAR esta programacao
qtd<-function(dados){
   
   cod<-c("C","R","V","S","A","I","L","D","T","N","O")
              
   n=length(cod)  ; N.dias<-matrix(0,nrow=n,ncol=2)
            
   for (i in seq_len(n)) {

      qtd_12h<-length(extracao_etapas2(dados)[[i]]$Servico_12h)

      qtd_24h<-length(extracao_etapas2(dados)[[i]]$Servico_24h)
                     
      N.dias[i,]<-c(qtd_12h,qtd_24h)
            }
 return(N.dias)
}

#install.packages("DT") ; install.packages("KableExtra")

library(DT) ; library(kableExtra) ; df3<-list()

mes<-c("jan","fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez")

for (j in 1:2){
   mat<-matrix(0,nrow=11,ncol=12) 
        for (i in 1:12){
             mat[,i]<-lapply(Cumprida,qtd)[[i]][,j]
         }
   df3[[j]]<-as.data.frame(mat) ; rownames(df3[[j]])<-cod ;colnames(df3[[j]])<-mes
}   
#-------------- No loop nao ta gerando. Verificar esse problema--------------#

## Serviços 12 horas
     datatable(df3[[1]],extensions = 'Buttons',
                       options = list(dom='Blfrtip',
                                 buttons=c('copy','csv','excel','pdf','print'),
                                 lengthMenu=list(c(5,7,9,-1),c(5,7,9,'Todas'))),
                       caption = "Quantidade de Serviços 12h no ano 2020")
 ## Serviços 24 horas   
     datatable(df3[[2]],extensions = 'Buttons',
                        options = list(dom='Blfrtip',
                                  buttons=c('copy','csv','excel','pdf','print'),
                                  lengthMenu=list(c(5,7,9,-1),c(5,7,9,'Todas'))),
                        caption = "Quantidade de Serviços 24h no ano 2020")

Planilhas Etapas

Problema: A programação conseguiu preencher, porém não está mantendo a formatação inicial da planilha. Falta resolver.

#install.packages("openxlsx")
library(openxlsx)

cod<-c("C","R","V","S","A","I","L","D","N","O") # retirando o Tuasco

## Leitura da Planilha de controle de Etapas jan/21
p<-read.xlsx("Escala_2021.01.xlsx",sheet = 10,startRow=7)

## Loop para preencher os dias (Em fase de teste)
for (i in seq_len(length(cod))){
  posicao<-extracao_etapas3("Escala_2021.01.xlsx")[[i]]$Servico_12h
  p[13:22,5:36][i,][posicao]<-"TD"
}

wb<-createWorkbook()
addWorksheet(wb,"Etapa_5x")
addWorksheet(wb,"Etapa_10x")
writeData(wb, "Etapa_5x",p)
saveWorkbook(wb, file= "minha_etapa_5xalt.xlsx", overwrite=TRUE)
Planilha Preenchida pelo software R

Planilha Preenchida pelo software R

Próximos Passos

  1. Melhorar a apresentação dos resultados;

  2. Criar gráficos e tabelas interativas com opção de exportação para excel, pdf, etc;

  3. Obter outras informações, tais como carga horária, quantidade de serviços, etc;

  4. Simplificar os códigos de programação caso seja possível;

  5. Incluir a leitura de dados na própria função.( Ok! Feito. )

  6. A partir da extração dos dias na escala de serviço cumprida, ler do excel (Office365, LibreOffice) as planilhas de etapas 5x e 10x em branco e incluir os dias extraídos (isto é, preencher as planilhas de etapas automaticamente), através do pacote xlxs abaixo: ( Em andamento! Vou concluir. )

Importação e Exportação

Importação e Exportação

  1. Integrar a extração de dados com a função de preenchimento do item 6) em uma só função.

Referências

R Core Team. 2020. R: A Language and Environment for Statistical Computing. Vienna, Austria: R Foundation for Statistical Computing. https://www.R-project.org/.
RStudio Team. 2020. RStudio: Integrated Development Environment for r. Boston, MA: RStudio, PBC. http://www.rstudio.com/.