Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sisprenatal #3

Open
silvadenisson opened this issue Nov 17, 2016 · 0 comments
Open

sisprenatal #3

silvadenisson opened this issue Nov 17, 2016 · 0 comments
Assignees

Comments

@silvadenisson
Copy link

sisprenatal <- function(years) {

sisprenatal <- data.frame()

for(i in years) {

# como a sequencia não está completa, coloquei pra baixar a lista completa de arquivos primeiro em um arquivo txt.
 download.file("ftp://ftp.datasus.gov.br/dissemin/publicos/SISPRENATAL/201201_/Dados/", file.path(tempdir(), "lista.txt"))
 lista <- readLines(file.path(tempdir(), "lista.txt"))
 lista <- substr(lista, nchar(lista) - 11, nchar(lista))
 lista <- data.frame(names = lista, ano = lista)
 lista$ano <- substr(lista$ano, 5, 6)
 lista$ano <- paste0(20, lista$ano)
  
 lista <- lista[lista$ano == i, ]
   
 for(y in 1:length(lista$ano)){   
  # Prepare local file names and remote download paths
  filenames  <- lista$names[y]
  
  localnames <- file.path(tempdir(), filenames)
  
  url.base   <- "ftp://ftp.datasus.gov.br/dissemin/publicos/SISPRENATAL/201201_/Dados"
  
  if( !file.exists(localnames) ) {
    # Try default path
    url <- paste(url.base, filenames, sep = "/" )
    
    if( download.file(url, destfile = localnames) ) {
      # Some of the files are postfixed as .DBC (uppercase), try again on error
      url <- paste(url.base, toupper(filenames), sep = "/" )
      download.file(url,  destfile = localnames )
    }
  }
  
  #  considerando ano 2000 como referencia
  fields     <- c("NUMERODN",
                  "LOCNASC",
                  "CODMUNNASC",
                  "IDADEMAE",
                  "ESTCIVMAE",
                  "ESCMAE",
                  "QTDFILVIVO",
                  "QTDFILMORT",
                  "CODMUNRES",
                  "GESTACAO",
                  "GRAVIDEZ",
                  "PARTO",
                  "CONSULTAS",
                  "DTNASC",
                  "SEXO",
                  "APGAR1",
                  "APGAR5",
                  "RACACOR",
                  "PESO",
                  "CODANOMAL"
  )
  
  
  
  # Load downloaded files into a data.frame
  df <- read.dbc::read.dbc(localnames, as.is = TRUE)
  
  # Select only applicable fields
  #df <- df[, fields]
  
  # This column is used as an indicator of which file originated the data
  df$dataset <- filenames
  
  sisprenatal <- rbind(df, sisprenatal, make.row.names = FALSE)
}
}

Returns data.frame

sisprenatal
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants