Last active
June 13, 2024 15:33
-
-
Save jjesusfilho/b8eb2ae1965676a06e0668819d832623 to your computer and use it in GitHub Desktop.
Baixa os microdados da rais
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Extrai os dados da rais com base na UF, no CNAE 2.0, no CBO e no Ano. | |
## O único argumento necessário é o ano. No entanto, a menos que sua memória ram tenha ao menos | |
rais<-function(uf=NULL,CNAE="",CBO="",ano=NULL){ | |
stopifnot(length(ano)==1,is.numeric(ano)) | |
u<-paste0("ftp://ftp.mtps.gov.br/pdet/microdados/RAIS/",ano,"/") | |
h <- curl::new_handle(dirlistonly=TRUE) | |
con <- curl::curl(u, "r", h) | |
tbl <- read.table(con, stringsAsFactors=FALSE, fill=TRUE) | |
close(con) | |
tbl<-tbl[str_which(tbl$V1,paste0(uf,collapse="|")),1] | |
urls <- paste0(u, tbl) | |
urls<-str_subset(urls,"[^(Estb|ESTB)]") | |
fls <- basename(urls) | |
fil<-str_replace(fls,"\\..*",".txt") | |
CNAE<-paste0(CNAE,collapse = "|") | |
CBO<-paste0(CBO,collapse = "|") | |
f<-function(x,pos){ | |
y<-str_which(str_trim(x$X9),paste0("^",CNAE)) | |
z<-str_which(str_trim(x$X8),paste0("^",CBO)) | |
x[intersect(y,z),] | |
} | |
c<-data.frame() | |
for (i in 1:length(fls)){ | |
file.remove(fls[i]) | |
file.remove(fil[i]) | |
download.file(urls[i],destfile = fls[i]) | |
system(paste0("7z X ",fls[i])) | |
a<-read_delim_chunked(fil[i], col_names=FALSE, DataFrameCallback$new(f), | |
chunk_size = 1000,delim=";") | |
if(ano<2015){ | |
names(a)<-paste0("X",1:45) | |
} | |
else{ | |
names(a)<-paste0("X",1:57) | |
} | |
if(nrow(a)>0) a$uf<-str_extract(fls[i],"\\D+") | |
a<-as.data.frame(a,stringsAsFactor=F) | |
c<-rbind(c,a) | |
file.remove(fls[i]) | |
file.remove(fil[i]) | |
} | |
return(c) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
qual o nome?