2

I have a panel data which contains 130 companies' departments in 15 years. The data includes the edge lists of these companies. How do I count every companies' hierarchical levels and identify every department's level in the hierarchy in 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

In this case, the top is A, and the bottom is K. The company's hierarchical level is 4. I hope I can create two variables in the panel data of the departments. Like this:

    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

2 Answers 2

Reset to default

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

1

Maybe try this:

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
')

convert to graph

g <- graph.data.frame(df)

get rank table: (you need to manually input the 'top' node)

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
1

You could use the data.tree package:

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")

This will give you:

       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         3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.