### "ENSb1315 Network analysis: social, ecological, and social-ecological approaches" ###
# Lecture: network analysis in R (first steps)
# Author: Harald Waxenecker
# Date: March 8, 2024


library(igraph) 




##### 1. Two-mode networks ######


# Number of nodes in the first and second modes
nodes_first_mode <- 30
nodes_second_mode <- 5

# Create a random bipartite graph
graph <- sample_bipartite(n1 = nodes_first_mode, n2 = nodes_second_mode, p = 0.5)

# Assign colors to the two modes
vertex_colors <- c(rep("lightblue", nodes_first_mode), rep("gold", nodes_second_mode))
V(graph)$shape <- c("square", "circle")[V(graph)$type+1]


# Plot the bipartite graph
plot(
  graph, 
  #layout = layout.bipartite(graph, types = V(graph)$type), 
  vertex.color = vertex_colors,
  vertex.label = NA,
  vertex.size=degree(graph),
  edge.size=4,
  edge.color="black",
  main = "Random Bipartite Network"
)






##### 2. Empirical network #####

# We need the "readxl" package to import an excel file
install.packages("readxl")
library(readxl)

# Here you need to insert the path to your working folder
setwd()


# import data
list.files()
edgelist <- read_excel("edgelist.xlsx")
attr_list <- read_excel("attr_list.xlsx")


# Create igraph object from edgelist
network <- graph_from_data_frame(edgelist, directed = TRUE)


# Verify if the nodes in the network and the names in the attribute list are in 
# the same order.
V(network)$name == attr_list$names

# They are not in the same order. So, we have to reorder the attribute list 
# based on the vertex names
attr_list <- attr_list[match(V(network)$name, attr_list$names), ]


# Let´s verify again! No it should be fine (all values = TRUE)
V(network)$name == attr_list$names


# Create vectors with the node attributes
gender <- attr_list$gender
climate_change <- attr_list$climate_change


# Assign gender attributes to nodes
V(network)$gender <- gender
V(network)$climate_change <- climate_change

# Create a vector of shapes based on the gender attribute values
node_shapes <- ifelse(V(network)$gender == 0, "square", "circle")


# Plot the directed friendship network
plot(network, 
     layout = layout_with_fr,  # Fruchterman-Reingold layout
     vertex.color = V(network)$climate_change,
     vertex.shape = node_shapes,
     vertex.label.color = "black",
     vertex.label.cex = 0.8,
     edge.arrow.size = 0.2,
     main = "Directed Friendship Network"
)





##### 3. Exercising #####

# Exercise 1
# Please, calculate different node centralities for our friendship network
# and export these outputs as a table.


# Exercise 2
# Please, create a directed random network with 10 nodes. Give some names 
# to the nodes, by assigning letters to nodes. 


# Exercise 3
# Please, can you provide an example of how network analysis could be applied in 
# your field of study?












