R/GADM2prep.R

#' Formats and prepares GADM2 located vaccination campaigns
#'
#' @param vc.GADM2 Cleaned GADM2 campaigns
#' @param shp2 This is a second administrative division shapefule that contains all the countries in the raw csv.
#' @examples
#' GADM2prep(cleaned$vc.GADM1)
#' @keywords internal


GADM2prep<-function(vc.GADM2,shp2){
  
  if(dim(vc.GADM2)[1]>0){
    
    #Running GADM code
    vc.test<-vc.GADM2
    vc.out.GADM2.unclean<-NULL
    
    #This loops through all of the rows of the dataframe and if it detects an na in the adm2 column
    #which we take to assume means the whole area was targeted, it repeats the line for all adm2 
    #locations and then inserts the adm2 value
    
    for(x in 1:dim(vc.test)[1]){
      if(!is.na(vc.test[x,"adm1"]) && is.na(vc.test[x,"adm2"])) {
        
        #Establish how many adm2 locations make up this adm1 location
        alladm2ofadm1<-as.data.frame(shp2[shp2$ISO==vc.GADM2[x,"country.code"] & shp2$ID_1==as.numeric(gsub("\\D", "", vc.test[x,"adm1"])),])
        #Make that many duplicates of the row entered in the csv
        for(i in 1:dim(alladm2ofadm1)[1]){
          vc.out.GADM2.unclean<-rbind(vc.out.GADM2.unclean,vc.GADM2[x,])
          vc.out.GADM2.unclean[(dim(vc.out.GADM2.unclean)[1]),"adm2"]<-as.character(alladm2ofadm1$SP_ID)[i]
          vc.out.GADM2.unclean
        }
      } else vc.out.GADM2.unclean<-rbind(vc.out.GADM2.unclean,vc.GADM2[x,])
      
    }
    
    cols.out<-c("vac.id","year","country","country.code","adm1","adm2","adm3","target.population","doses",
                "coverage.planned","coverage.adm","coverage.survey","agemin","agemax","campaign.type","scenario","skew","adm2.prop","location.encoding")
    
    #Match the columns with what we have
    mm<-match(cols.out, names(vc.out.GADM2.unclean))
    
    #Set a dummy dataframe with the correct names and dimensions
    vc.out.GADM2<-data.frame(matrix(rep(NA,dim(vc.out.GADM2.unclean)[1]*length(cols.out)),ncol=length(mm)))
    names(vc.out.GADM2)<-cols.out
    
    #Feed in the data in the correct order
    for(x in 1:length(mm)){
      if(!is.na(mm[x])) vc.out.GADM2[,x]<-vc.out.GADM2[,mm[x]]
    }
    
    #Set the levels
    #Sets the level of adm values
    lvlGADM2<-rep(3, nrow(vc.out.GADM2))
    lvlGADM2[is.na(vc.out.GADM2$adm3)]<-2
    lvlGADM2[is.na(vc.out.GADM2$adm2)]<-1
    lvlGADM2[is.na(vc.out.GADM2$adm1)]<-0
    vc.out.GADM2
  }
  
}
arranhamlet/popvac_package documentation built on May 10, 2019, 1:48 p.m.