---
  title: "Calculo del indice de similitud Jaccard"
author: "Joaquin Jimenez Puerto"
date: "12 de junio de 2018"
output:
  html_document: default
pdf_document: default
---
  
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
# function by https://stats.stackexchange.com/questions/49453/calculating-jaccard-or-other-association-coefficient-for-binary-data-using-matri
# modified by Agustin Diez (June 2, 2017):
# modified by Joaquin Jimenez Puerto (Feb 27, 2019):
#             * Turned into .Rmd
#             * Adapted to Gephi
#             * Questions translated into spanish
#             * The .csv needs to present the variables in a 1-0 fashion. No counts.

library(Matrix)
jaccard <- function(m) {
    ## common values:
    A = tcrossprod(m)
    ## indexes for non-zero common values
    im = which(A > 0, arr.ind=TRUE)
    ## counts for each row
    b = rowSums(m)
    
    ## only non-zero values of common
    Aim = A[im]
    
    ## Jacard formula: #common / (#i + #j - #common)
    J = sparseMatrix(
    i = im[,1],
    j = im[,2],
    x = Aim / abs((b[im[,1]] + b[im[,2]] - Aim)),
    dims = dim(A)
    )
    
    return( J )
}

# Obtain input table

br.tab1 <- read.table(file='jaccard1.csv', sep=',', header=T, row.names=1, quote = "") # INPUT FILE NAME IN THIS LINE
#If there are extra variables uncomment the next two lines as needed
br.tab1[is.na(br.tab1)] <- 0 #Na = 0
#br.tab1<-br.tab1[,9:ncol(br.tab1)] #Drop columns with no relevant information


# Ask for a minimum value to generate a link
choose.min_value <- function(){readline("Introduce un valor minimo para crear un enlace (0-1): ")}
min_value <- choose.min_value()

# Output to file
br.dat<-jaccard(as.matrix(br.tab1))
br.dat[lower.tri(br.dat)] <- NA
diag(br.dat) <- 0
br.dat<-as.matrix(br.dat)
br.dat[br.dat<min_value]<-0
dimnames(br.dat)<-list(rownames(br.tab1),rownames(br.tab1))

#rownames(br.dat)<-rownames(br.tab1)
write.table(br.dat, 'Habitat_out.csv',sep=";",quote=F,col.names=NA,na="")
#system("sed 's/\"\"//g' JACC_out.csv | tee JACC_out2.csv")
# end of script
```