rm(list=ls())
setwd('D:\\areas_protegidas\\xls_dbf')
# install.packages("ineq")
library(ineq)
library(foreign) # para poder leer el dbf


################################################################################
# ECOREGION * PAIS

dat <- read.dbf('ecoregiones_paises_historico_final.dbf')
dat <- dat[-c(30,176,143,187:190),] # saco FK y titicaca

#######################################################################
# sumo por la columna de dat[,2]

dat_all <- aggregate(dat[,4:19],by=list(dat$ECO), sum)
dat_all <- as.data.frame(dat_all)
dat_all$PAIS <- "All countries"
dat_all$PAIS_ECO <- "NULL"
colnames(dat_all)[1] <- "ECO" 

# y agrego las nuevas filas a dat
dat <- rbind(dat, dat_all)
dat <- as.data.frame(dat)
#######################################################################

giniAP <- NULL
giniAP_lleno <- NULL
giniFP <- NULL
giniFP_lleno <- NULL

pais <- c("All countries","Argentina","Bolivia","Brazil","Chile","Colombia",
          "Ecuador","Guayana_Fra","Guyana","Peru",
          "Paraguay","Suriname","Uruguay","Venezuela","Guayanas")


# area protegida IUCN 1a4
for (j in 6:12){
  dat_decada <- data.frame(dat[,1], dat[,j],j-5)
  colnames(dat_decada) <- c("pais","AP","decada")
  for(i in pais) {   
    dat_pais <- subset(dat_decada, dat_decada$pais == i)
    giniAP$pais[which(pais==i)] <- i 
    giniAP$decada[which(pais==i)] <- j-5
    giniAP$giniAP[which(pais==i)] <- ineq(dat_pais$AP, type = "Gini", na.rm = TRUE)
        }
  giniAP <- as.data.frame(giniAP)
  giniAP_lleno <- rbind(giniAP_lleno, giniAP)
}


# # fraccion protegida IUCN 1a4
for (j in 13:19){
  dat_decada <- data.frame(dat[,1], dat[,j],j-12)
  colnames(dat_decada) <- c("pais","FP","decada")
  for(i in pais) {   
    dat_pais <- subset(dat_decada, dat_decada$pais == i)
    # giniFP$pais[which(pais==i)] <- i 
    # giniFP$decada[which(pais==i)] <- j-12 
    giniFP$giniFP[which(pais==i)] <- ineq(dat_pais$FP, type = "Gini", na.rm = TRUE)
  }
  giniFP <- as.data.frame(giniFP)
  giniFP_lleno <- rbind(giniFP_lleno, giniFP)
}

union <- cbind.data.frame(giniAP_lleno, giniFP_lleno)

write.table(union, file="salidas txt/gini_eco_pais_historico.txt", sep=";", row.names=T)