sebastian.klotz
sebastian.klotz

Reputation: 125

How to attach attributes to a list of network objects?

I have a list of network objects and a list of dataframes that include vertex attributes. I would like to attach the vertex attributes to the network objects.

In the code below I show how to complete this task for each network object individually. However, I cannot figure out how to complete this task when I have the network objects and vertex attribute dataframes in lists. In reality, I have a large number of network objects which is why I would like to use lists. I have tried to use lapply but couldn't figure out the solution.

# Use the network library
library("network")

# Create first dataset
data_frame_1 = data.frame(event1 = c(1, 2, 1, 0),
                          event2 = c(0, 0, 3, 0),
                          event3 = c(1, 1, 0, 4),
                          row.names = letters[1:4])

# Transform first dataset to matrix and to network
data_matrix_1 <- as.matrix(data_frame_1)
data_network_1 <- as.network(data_matrix_1, matrix.type='bipartite', loops=FALSE, directed = FALSE, ignore.eval=FALSE, names.eval='weight')

# Create first vertex attribute dataset
attribute_1 = data.frame(attribute1 = c(2, 5, 7, 1), attribute2 = c(4, 1, 0, 2), row.names = letters[1:4])

# Attach attributes to network
data_network_attr_1 <- network::set.vertex.attribute(data_network_1, names(attribute_1), attribute_1)


# Create second dataset
data_frame_2 = data.frame(event1 = c(0, 1, 2, 0),
                          event2 = c(0, 3, 1, 0),
                          event3 = c(4, 2, 0, 1),
                          row.names = letters[1:4])

# Transform second dataset to matrix and to network
data_matrix_2 <- as.matrix(data_frame_2)
data_network_2 <- as.network(data_matrix_2, matrix.type='bipartite', loops=FALSE, directed = FALSE, ignore.eval=FALSE, names.eval='weight')

# Create second vertex attribute dataset
attribute_2 = data.frame(attribute1 = c(4, 1, 2, 1), attribute2 = c(5, 0, 2, 1), row.names = letters[1:4])

# Attach attributes to network
data_network_attr_2 <- network::set.vertex.attribute(data_network_2, names(attribute_2), attribute_2)


# Repeat the previous steps using lists.

# Create a list of the two networks
list_dataframe <-list(data_frame_1, data_frame_2)
list_matrix <- lapply(list_dataframe, as.matrix)
list_network <- lapply (list_matrix, as.network, matrix.type='bipartite', loops=FALSE, directed = FALSE, ignore.eval=FALSE, names.eval='weight')

# Create a list of the two attribute datasets

list_attributes <-list(attribute_1, attribute_2)

# How do I attach the list of attributes to the list of networks?

Upvotes: 1

Views: 258

Answers (1)

akrun
akrun

Reputation: 887391

We can use Map to do this on the corresponding list elements

out <- Map(function(x, y) network::set.vertex.attribute(x, names(y), y), 
          list_network, list_attributes)

Upvotes: 1

Related Questions