同一网络不同时间段的特征向量值(R中的igraph)

Eigenvector values for different time periods of same network (igraph in R)

这里是全R菜鸟,还请大家多多包涵!

我有特定时期内国家间贸易的双年数据。我正在尝试计算 1946 年至 2014 年期间每个单独年份中每个国家/地区的特征向量中心值。其次,我想将所有这些特征值(带有案例标签和年份)整齐地打包在一个可以导出为 CSV 的数据框中。

以边为例:

links <- structure(list(ccode1 = c(2L, 3L, 4L, 5L, 2L, 3L, 4L, 5L, 2L, 
3L, 4L, 5L), ccode2 = c(5L, 4L, 3L, 2L, 5L, 4L, 3L, 2L, 
5L, 4L, 3L, 2L), year = c(1960, 1960, 1960, 1960, 1961, 1961, 1961, 1961, 1962, 1962, 1962, 1962), weight = c(1347.34, 778.42999, 
866.85999, 1014.14, 895.46002, 1082.0699, 1584.7, 1193.37, 1355.3101, 
1348.75, 3653.54, 616.98999)), row.names = c(NA, 12L), class = "data.frame")

网络构建如下:

network <- graph_from_data_frame(links, directed = FALSE, vertices = NULL)

特征值的计算方式如下:

trade.eigen <- eigen_centrality(network, directed = FALSE)

1.如何自动计算每个国家每年的特征值?

2。我如何将所有这些值与国家/地区标签和年份组合在一个数据框中?

感谢您提供易于重现的示例。如果我正确理解你的问题,你需要做的就是:

  1. 每年迭代
  2. 过滤掉不具有与您迭代的年份关联的边属性的边
  3. 计算过滤图的特征值
  4. 将输出存储在单个数据框中

tidyverse 包系列有很多实用函数可以让这一切变得简单。使用map进行迭代,使用enframe将格式从key-value格式更改为data frame 格式,然后使用 unnest 清理。

# install.packages('tidyverse')
library(tidyverse)


#let's get all unique values for year
#we can do this by pulling the edge attribute
#"year" frome the graph "network"
years <- E(network)$year %>%
  unique


#now we want to use purrr's map to iterate through all the years
#the goal is to only keep edges from a year we are interested in
#"map" returns a list, and if we use the function "setNames", then
#each item in the list will be named after the object we are iterating
eigen_by_year <- purrr::map(setNames(years, years), function(yr){
  #here we filter away all edges that aren't from the year we are interested
  network_filtered = network - E(network)[year != yr]

  #we now calculate the eigen values for the filtered network
  eigen_values <- eigen_centrality(network_filtered, directed = F)$vector

  #"eigen_values" is a named vector, let's convert this named vector
  #into a data frame with the name column being the vertex name
  #and the value column being the eigen value
  tibble::enframe(eigen_values)
})

#The result is a list where the item names are the years
#and they contain a data frame of the eigen values associated
#with their years
eigen_by_year

#let's use enframe one more time so that the name of the list items
#are now their own "name" column and the nested data rames are
#in the "value" column" we will need to use unnest to flatten the dataframe
eigen_data_frame <- eigen_by_year %>%
  tibble::enframe() %>%
  tidyr::unnest()

eigen_data_frame

希望对您有所帮助。