rm(list=ls())
library(ineq)
library(randomForest)
setwd('D:\\areas_protegidas\\xls_dbf')
# setwd("/home/marcos/grive/baldi_ecoaustral")
dat<-read.table('todas_las_variables_sam_simp_fk_1000km.txt',sep='\t',header=T)

dat$AREA_AL <-  rowSums(dat[,21:33]) # creo el area para todo el continente
dat$AP_AL <- rowSums(dat[,35:47]) # creo el area protegido para todo el continente
dat<-data.frame(dat[,c(1:34,49,35:48,50)])  # muevo las columnas

dat<-dat[,c(20,17,13,14,16,21:50)]


# paises <- c("AR","BO","BR","CL","CO","EQ","GF","GU","PE","PY","SU","UY","VZ","GI","AL")
# variables<-c("PPT","TMP","ELEV","SLOPE","POP","DIST_ROAD","ACCESS","CULTIVOS",
#              "DIST_FRON","DIV_AN","BIOMASS","TEB","FLICKR_POP")


# cuando no consideramos el factor de ponderacion

RF<-matrix(nrow = 5)

for (i in 21:35){
  dat_simp <- data.frame(dat[,1:5], dat[,i], stringsAsFactors = FALSE)
  dat_pais <- subset(dat_simp, dat_simp[,6]>0)
  
    # calculo del random forest    
  random<-randomForest(dat_pais$dat...i.~., type='regression',
                   sampsize=floor(length(dat_pais$dat...i.)*5/100), 
                   data=dat_pais, ntree=50, mtry=5, importance=T)
  
  IncMSE<-data.frame(random$importance[,1])
  names(IncMSE)<-substr(names(dat)[i],4,5) # aca del campo AREA_PAIS se extrae el nombre del pais
  
  RF<-cbind(RF, IncMSE)
}

write.table(RF, "salidas txt/RF_sin_ponderacion.txt",col.names=T, row.names=T)


# cuando sí consideramos el factor de ponderacion

# for (i in 6:20){
#     dat_simp <- data.frame(dat[,1:5], dat[,i], dat[,(i+15)], stringsAsFactors = FALSE)
#     dat_pais <- subset(dat_simp, dat_simp[,6]>0)
#     # names(dat_pais) <- c(names(dat)[1:5], names(dat)[i], names(dat)[c(i+15)])
#     # print(head(dat_pais))
# 
#     # nom_pais<-substr(names(dat)[i],6,7) # aca del campo AREA_PAIS se extrae el nombre del pais
#     # print(nom_pais)
#     
#     write.table(dat_pais, file=paste("todas_las_variables_", nom_pais, ".txt"), col.names=T, row.names=T)
#   
#     
#     # lo que tendría que hacer es calcular el RF con los 
#     # datos de AP_x, y el factor de ponderacion con el AREA_x
#     
#      # calculo del random forest    
#     RF<-randomForest(dat_pais$dat....i...15..~., type='regression',
#                      sampsize=floor(length(dat_pais$dat....i...15..)*5/100), 
#                      data=dat_pais, ntree=50, mtry=5, importance=T)
#     RF$importance
# }

# colnames(gini_AP)<- colnames(gini_FP)<- colnames(datos_gini_AP) <- colnames(datos_gini_FP) <- nom_gini
# write.table(datos_gini_AP, "salidas txt/datos_gini_AP.txt",col.names=T, row.names=F)
# write.table(datos_gini_FP, "salidas txt/datos_gini_FP.txt",col.names=T, row.names=F)
# write.table(gini_AP, "salidas txt/gini_AP.txt",col.names=T, row.names=F)
# write.table(gini_FP, "salidas txt/gini_FP.txt",col.names=T, row.names=F)