首页 > 解决方案 > 使用 R 按滚动周期绘制网络图

问题描述

我试图通过滚动三年来进行网络图和一些统计,但我不知道如何设置滚动功能。下面是我没有滚动的编码。

> library(igraph)
> em <- read.csv(file.choose(), header = TRUE )
> network <- graph.data.frame(em, directed = TRUE )
> em
   sender receiver weights year
1       a        d       2 2001
2       b        a       3 2001
3       c        a       1 2001
4       d        h       1 2001
5       e        d       3 2001
6       a        b       1 2002
7       b        c       2 2002
8       c        d       1 2002
9       d        a       1 2002
10      e        h       2 2002
11      a        d       1 2003
12      b        d       1 2003
13      c        a       2 2003
14      d        h       2 2003
15      e        a       1 2003
16      a        d       1 2004
17      b        c       1 2004
18      c        d       2 2004
19      d        c       1 2004
20      e        a       2 2004
> E(network)$weight <- as.numeric(network[,3])
Warning message:
In eattrs[[name]][index] <- value :
  number of items to replace is not a multiple of replacement length
> p <- plot (network,edge.width=E(network)$weight)

所以在这个例子中,它最终会得到一个加权网络图。我想使用 2001-2003 年和 2002-2004 年子样本中的数据绘制图表,并进一步使用一些 SNA 统计数据。一些在线资源建议 -rollappy()- 或包 -tidyquant- 中的函数可以,但我没有设法弄清楚我们如何将第 4 列识别为年份以及如何设置滚动周期。如果有人能提供帮助,将不胜感激,因为我是 R 的新手。

非常感谢!!

标签: rigraphrolling-computation

解决方案


感谢@emilliman5 提出更多问题。

我的真实数据集是一个 15 年时间跨度的不平衡面板。我打算使用部分完整数据来绘制网络图。减法规则是 3 年滚动期(实际上还有其他一些条件,但我只是在这里问滚动)。所以我打算先调用滚动子样本并进行图表。我希望现在有点清楚了。

以上数据只是一个模拟样本。4 年的范围应生成两张图(2001-2003、2002-2004),15 年的范围应生成 13 张图。真正的加权变量不称为权重,但我同意“as.numeric(network[,3])”这一行是多余的。(我现在意识到我做的例子不好......对不起......)

我现在有人帮助我,所以我将发布一些代码。希望它可以帮助其他人。

方法一:按函数调用子样本。这使我免于与图形一起构建嵌套循环。

# Function: conditions for substracting; here rolling-year only
f <- function(j){                 
df <- subset(em, year>=j & year <= j+2)
}

print (f(2001))                  # Test function output, print-out

# Rolling by location and year, graph-plotting
for (j in 2001:2002){
sdf = f(j)                              
nw <- graph.data.frame(sdf, directed = TRUE)
plot(nw, edge.width = E(sdf[[j]])$weight)
}

方法 2:使用循环——对于一个或两个减法条件很好,但对于更多的情况会有点笨拙。

c <- 2001                       # a number for year count
sdf <- {}                       # Set an empty set to save subsets
for (j in 2001:2002){
df_temp <- subset(em, year>=j & year<=j+2)
print(nrow(df_temp))            # To check the subset, not necessary
sdf[[c]] <- cbind(df_temp)
nw <- graph.data.frame(sdf[[c]], directed = TRUE)
plot(nw, edge.width = E(sdf[[c]])$weight)
c <- c + 1
}

推荐阅读