如何将属性附加到网络对象列表?

时间:2019-06-24 09:26:29

标签: r

我有一个网络对象列表和一个包含顶点属性的数据帧列表。我想将顶点属性附加到网络对象。

在下面的代码中,我演示了如何分别为每个网络对象完成此任务。但是,当列表中包含网络对象和顶点属性数据框时,我无法弄清楚如何完成此任务。实际上,我有大量的网络对象,这就是为什么我要使用列表的原因。我尝试使用lapply,但找不到解决方法。

# 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?

1 个答案:

答案 0 :(得分:1)

我们可以使用Map在相应的list元素上进行

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