user3388408
user3388408

Reputation: 131

Add labels to vertex by matching ID in a frame to the vertex names?

I have an igraph where the vertexes only have their IDs (V(g)$name). I also have a data.frame in this format that match each ID to a name:

ID   name
1    Ann
2    Bob
3    Carl
...

I would like to add the names to the vertex (V(g)$label) by matching the ID. The graph does not have all the IDs the names frame has.

I think it should be rather simple but as I'm new to R I'm not quite sure as how to do it.

Upvotes: 1

Views: 307

Answers (1)

lukeA
lukeA

Reputation: 54247

As suggested in the comments, match could do the trick:

df <- read.table(header=T, text="
ID   name
1    Ann
2    Bob
3    Carl
4    Linda
5    Peter")
library(igraph)
g <- sample_pa(4)
V(g)$label <- as.character(df$name[match(V(g), df$ID)])

Upvotes: 1

Related Questions