Carrega bibliotecas

library(tidyverse)
library(lubridate) # dates
library(fs) # file system
library(stringi) # for %s+%
library(furrr) # parallel processing
library(zip) # zip files
library(tictoc) # timing
source("util.R") # low-level functionality

Lista .zips em diretorio de dados

data_dir <- "data"
dir_ls(data_dir,regexp=".*zip")
#> data/Despesas MRJ.zip

Lista conteúdo do zip

fname_zip <- dir_slash_fname(data_dir,"Despesas MRJ.zip")
fnames_in_zip <- zip_list(fname_zip)
fnames_in_zip

Análise do primeiro arquivo no .zip

fname1 <- fnames_in_zip$filename[1]
zip::unzip(fname_zip,files=fname1,exdir=data_dir)
dir_ls(data_dir,regexp="*.TXT")
#> data/MP_EMPENHOS_201401.TXT

Adivinha o encoding do arquivo

fname1_txt <- dir_slash_fname(data_dir,fname1) %>%
  path_norm
guess_encoding(fname1_txt)

Localização típica p/ dados brasileiros

locale_bra <- locale(encoding="ISO-8859-1",
                     decimal_mark = ",",
                     date_format="%d/%m/%Y")

Olha para as primeiras 2 linhas

first2 <- read_lines(fname1_txt,n_max=2,
                     locale=locale_bra) %>%
  str_squish() 
first2
#> [1] "Poder;Grupo;Modalidade;Elemento;NomeElemento;SubElemento;NomeSubElemento;Orgao;NomeOrgao;UO;NomeUO;UG;NomeUG;Credor;NomeCredor;FonteRecursos;NomeFonteRecursos;Processo;Funcao;NomeFuncao;SubFuncao;NomeSubFuncao;Programa;NomePrograma;Acao;NomeAcao;Licitacao;Data;TipoAto;Valor;Exercicio;EmpenhoExercicio;Liquidacao;Pagamento;Historico;Banco;NomeBanco;Agencia;ContaCorrente;NomeContaCorrente;ASPS;MDE;ExercicioContrato;NumeroContrato;ObjetoContrato;"                                                                                                                                                                                                                                                                                                                                                              
#> [2] "Executivo;OUTRAS DESPESAS CORRENTES;APLICACOES DIRETAS;30;MATERIAL DE CONSUMO;27;MATERIAIS DE PROTECAO E SEGURANCA;4351;Companhia Municipal de Limpeza Urbana;4351;Companhia Municipal de Limpeza Urbana;4351;Companhia Municipal de Limpeza Urbana;7913842000183;DMX DO BRASIL COMERCIO LTDA ME;100;ORDINARIOS NAO VINCULADOS;15043092013;15;URBANISMO;122;ADMINISTRACAO GERAL;0385;GESTAO ADMINISTRATIVA - MEIO AMBIENTE E SUSTENTABILIDADE;4165;APOIO ADMINISTRATIVO - ADM. INDIRETA - MEIO AMBIENTE E SUSTENTABILIDADE;PREGÃO;02/01/2014;EMPENHO;5183,200000;2014;48/2014;;;AQUISIÇÃO DE CONE, POR SOLICITAÇÃO DA FGX -ITENS -01 E 02 -PRAZO DE PAGAMENTO - 30 DIAS APÓS A ENTREGA DO MATERIAL -DEMAIS CONDIÇÕES E ESPECIFICAÇÕES CONFORME EDITAL E SEUS ANEXOS;1;BANCO DO BRASIL S/A;2234;73067;CONTA MOVIMENTO;N;N;;;;"

Conta separadores nas primeiras duas linhas

first2 %>% cnt_seps(";")

Contabiliza separadores em todas as linhas: Note que a maioria tem 45 mas algumas linhas tem 46 e 48 separadores

read_lines(fname1_txt,
           locale=locale_bra) %>%
  cnt_seps(";")

Mostre quais linhas tem separadores anomalos

cnt_seps_df(fname1_txt,locale_bra,";",45,5)

Verifica truncagem de todas as linhas para o numero correto de colunas (46)

trunc_cols(fname1_txt,locale_bra,
           max_cols=46,sep=";",n_max=10)%>%
  cnt_seps(";")

Obtém lista de todos os arquivos no zip e deleta .rds com o mesmo nome se existirem

fnames <- zip_list(fname_zip) %>% pull(filename)
repl_ext(fnames,"rds") %>%
  dir_slash_fname(data_dir,.) %>%
  walk(~if(file_exists(.))file_delete(.))

Converte arquivos no .zip para .rds

Trunca colunas, usando processamento paralelo do library(furrr)

tic()
plan(multiprocess)
# fnames[2] %>% 
fnames %>% future_map_chr(unzip_trunc_rds,
                          fname_zip,data_dir,locale_bra,45)
toc()

Examina o primeiro rds

fname_rds1 <- dir_ls(data_dir,regexp="MP_EMPENHOS_\\d{6}.*rds") %>%
  sort %>%
  first
df_rds1 <- fname_rds1 %>% read_rds
dim(df_rds1)
#> [1] 31694    45

Com glimpse

glimpse(df_rds1)
#> Observations: 31,694
#> Variables: 45
#> $ Poder             <fct> Executivo, Executivo, Executivo, Executivo, Ex…
#> $ Grupo             <fct> OUTRAS DESPESAS CORRENTES, OUTRAS DESPESAS COR…
#> $ Modalidade        <fct> "APLICACOES DIRETAS", "APLICACOES DIRETAS", "A…
#> $ Elemento          <fct> 39, 39, 52, 39, 39, 39, 39, 39, 39, 39, 39, 52…
#> $ NomeElemento      <fct> OUTROS SERVICOS DE TERCEIROS - PESSOA JURIDICA…
#> $ SubElemento       <fct> 77, 04, 01, 07, 13, 78, 77, 04, 04, 19, 78, 03…
#> $ NomeSubElemento   <fct> "MANUTENCAO E SUPORTE DE SOFTWARE", "SERVS.DE …
#> $ Orgao             <dbl> 3041, 3041, 3041, 3041, 3041, 3041, 3041, 3041…
#> $ NomeOrgao         <fct> Fundação Planetário da Cidade do Rio de Janeir…
#> $ UO                <dbl> 3041, 3041, 3041, 3041, 3041, 3041, 3041, 3041…
#> $ NomeUO            <fct> Fundação Planetário da Cidade do Rio de Janeir…
#> $ UG                <dbl> 3041, 3041, 3041, 3041, 3041, 3041, 3041, 3041…
#> $ NomeUG            <fct> Fundação Planetário da Cidade do Rio de Janeir…
#> $ Credor            <fct> 860640000171, 2270703000165, 31978612000187, 6…
#> $ NomeCredor        <fct> INGRESSO.COM SA, HIDROLIGHT EQUIPAMENTOS E SER…
#> $ FonteRecursos     <dbl> 200, 200, 408, 200, 200, 200, 200, 200, 200, 2…
#> $ NomeFonteRecursos <fct> "RECEITA PROPRIA DE AUTARQUIAS, FUNDACOES E EM…
#> $ Processo          <fct> 126000472010, 126003602012, 126003292013, 1260…
#> $ Funcao            <fct> 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13…
#> $ NomeFuncao        <fct> CULTURA, CULTURA, CULTURA, CULTURA, CULTURA, C…
#> $ SubFuncao         <fct> 126, 122, 126, 122, 122, 126, 126, 573, 122, 3…
#> $ NomeSubFuncao     <fct> TECNOLOGIA DA INFORMACAO, ADMINISTRACAO GERAL,…
#> $ Programa          <fct> 0397, 0387, 0397, 0387, 0387, 0397, 0397, 0310…
#> $ NomePrograma      <fct> "GESTAO DOS SERVICOS E SISTEMAS INFORMATIZADOS…
#> $ Acao              <dbl> 4757, 4167, 4757, 4167, 4167, 4757, 4757, 4506…
#> $ NomeAcao          <fct> "MANUTENCAO E DESENVOLVIMENTO DA INFORMATICA -…
#> $ Licitacao         <fct> DISPENSA, DISPENSA, DISPENSA, DISPENSA, PREGÃO…
#> $ Data              <date> 2014-01-01, 2014-01-01, 2014-01-01, 2014-01-0…
#> $ TipoAto           <fct> PAGAMENTO DE RPP, PAGAMENTO DE RPP, PAGAMENTO …
#> $ Valor             <dbl> 416.00, 665.00, 8000.00, 4014.18, 10000.32, 32…
#> $ Exercicio         <dbl> 2013, 2013, 2013, 2013, 2013, 2013, 2013, 2013…
#> $ EmpenhoExercicio  <fct> 84/2013, 13/2013, 269/2013, 211/2013, 237/2013…
#> $ Liquidacao        <dbl> 3, 9, 1, 3, 3, 1, 1, 8, 1, 2, 8, 1, 56, 4, 37,…
#> $ Pagamento         <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
#> $ Historico         <fct> "LOCACÃO DE SISTEMA DE AUTOMAÇÃO DE BILHETERIA…
#> $ Banco             <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
#> $ NomeBanco         <fct> BANCO DO BRASIL S/A, BANCO DO BRASIL S/A, BANC…
#> $ Agencia           <dbl> 2234, 2234, 22349, 2234, 2234, 2234, 2234, 223…
#> $ ContaCorrente     <fct> 10146, 10146, 298332X, 10146, 10146, 10146, 10…
#> $ NomeContaCorrente <fct> BCO BRASIL C/C 1.014-6, BCO BRASIL C/C 1.014-6…
#> $ ASPS              <fct> N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N…
#> $ MDE               <fct> N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N…
#> $ ExercicioContrato <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, 2013, NA, …
#> $ NumeroContrato    <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, 16, NA, NA…
#> $ ObjetoContrato    <fct> NA, NA, NA, NA, NA, NA, NA, NA, NA, "CONTRATAÇ…

Verifica cardinalidade das colunas nao numericas

df_rds1 %>% get_card_fact

Combina todos os data frames num só usando “purrr::map_dfr”

fnames_rds <- dir_ls(path=data_dir,regexp="\\d{6}\\.rds$")
df_all <- fnames_rds %>%
  map_dfr(read_rds) %>%
  mutate_if(is.character,as.factor) %>%
  arrange(Data)
dim(df_all)
#> 2252570      45

Deleta todos menos o primeiro (para inspeção)

fnames_rds %>% tail(-1) %>% walk(file_delete)

Salva data frame com todos os dados num .rds compactado

fname_rds <- dir_slash_fname(data_dir,"MP_EMPENHOS_ALL.rds")
df_all %>% write_rds(fname_rds, compress="bz")

Compara tamanho dos arquivos

c(fname_zip,fname1_txt,fname_rds) %>%
  map_dfr(~tibble(file=.x,
                  size=file_size(.x)%>%as.character))