在这里完成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。以及如何将所有这些值以及国家/地区标签和年份合并到一个数据框中?
答案 0 :(得分:1)
感谢您提供一个易于复制的示例。如果我正确理解了您的问题,那么您要做的就是:
tidyverse 软件包家族具有许多实用程序功能,可简化此操作。使用 map 进行迭代,使用 enframe 将格式从键值格式更改为数据框格式,然后使用不必要清理。
# 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
我希望这会有所帮助。