我有一个面板数据,其中包含了15年来130个公司的部门。这些数据包括这些公司的边缘列表。我如何计算每个公司的层级,并在R中识别层级中的每个部门的层级?
source target
1 A B
2 A C
3 A D
4 B E
5 B F
6 C G
7 D H
8 D I
9 D J
10 G K在本例中,顶部是A,底部是K。公司的层级是4。我希望我可以在部门的面板数据中创建两个变量。如下所示:
year compname department complevel departlevel
1 2000 Ben Corp. A 4 1
2 2000 Ben Corp. B 4 2
3 2000 Ben Corp. C 4 2
4 2000 Ben Corp. D 4 2
5 2000 Ben Corp. E 4 3
6 2000 Ben Corp. F 4 3
7 2000 Ben Corp. G 4 3
8 2000 Ben Corp. H 4 3
9 2000 Ben Corp. I 4 3
10 2000 Ben Corp. J 4 3
11 2000 Ben Corp. K 4 4发布于 2016-04-12 01:01:52
也许你可以试试这个:
library(igraph)
df <- read.table(text = '
source target
1 A B
2 A C
3 A D
4 B E
5 B F
6 C G
7 D H
8 D I
9 D J
10 G K
')转换为图形
g <- graph.data.frame(df)获取排名表:(需要手工输入top节点)
data.frame(node = names(shortest.paths(g)[,'A']), rank = shortest.paths(g)[,'A']+1)
node rank
A A 1
B B 2
C C 2
D D 2
G G 3
E E 3
F F 3
H H 3
I I 3
J J 3
K K 4发布于 2016-04-17 19:24:10
您可以使用data.tree包:
library(data.tree)
df <- read.table(text = '
source target
1 A B
2 A C
3 A D
4 B E
5 B F
6 C G
7 D H
8 D I
9 D J
10 G K
')
tree <- FromDataFrameNetwork(df)
print(tree, "level")这将为您提供:
levelName level
1 A 1
2 ¦--B 2
3 ¦ ¦--E 3
4 ¦ °--F 3
5 ¦--C 2
6 ¦ °--G 3
7 ¦ °--K 4
8 °--D 2
9 ¦--H 3
10 ¦--I 3
11 °--J 3https://stackoverflow.com/questions/36554205
复制相似问题