### DNA sample data ###

# loading data exported from DNA sample database
data <- as.matrix( read.csv("export.csv", header = T, row.names = 1, sep = ";") )
data

# recoding the negative values for the visualization purposes
mat <- data
mat[mat == -1] <- 1
mat

# creating color coding for positive and negative ties
col <- rep("lightgreen", sum(mat))
col[ which(data[data!=0]==-1) ] <- "orangered"
col

library(sna)

# plotting a two-mode network
set.seed(7)
gplot(mat, gmode = "twomode", usearrows = F,
      edge.col = col, vertex.border = F,
      displaylabels = T, label.pos = 5, vertex.rot = 45)

# calculating Euclidean distances for actors
row_mat_dist <- dist(data, method = "euclidean")
row_dist <- as.matrix(row_mat_dist)
row_dist

# calculating Euclidean distances for concepts
col_mat_dist <- dist( t(data), method = "euclidean")
col_dist <- as.matrix(col_mat_dist)
col_dist

# using hierarchical clustering to group the actors and concepts
?hclust
row_hclust <- hclust(row_mat_dist, method = "ward.D2")
col_hclust <- hclust(col_mat_dist, method = "ward.D2")

library(gplots)

# generating row and column dendrograms
row_dend <- as.dendrogram(row_hclust)
col_dend <- as.dendrogram(col_hclust)

# plotting a heatmap
png("heatmap.png", width = 2400, height = 2000, units = "px", res = 300) 

heatmap.2(data,
          Rowv = row_dend,  # row dendrogram
          Colv = col_dend,  # column dendrogram
          scale = "none",  # scale by row (optional)
          trace = "none",  # no trace lines inside the heatmap
          dendrogram = "both",  # show both row and column dendrograms
          col = redgreen(75),  # color scheme
          cexRow = 0.8,           # adjust row label size
          cexCol = 0.8,           # adjust column label size
          lwid = c(1.5, 4),       # column widths (left dendrogram, heatmap)
          lhei = c(1.5, 4),       # row heights (top dendrogram, heatmap)
          key = TRUE,             # show color key
          margins = c(20, 20),    # margins
          density.info = "none")  # no density information

dev.off()

# end of script
