Scott
Scott

Reputation: 51

R igraph: can't set the attributes of an edge sequence

I'm trying to manipulate the attributes of a subset of edges in an igraph object in R using edge_attr (or alternatively, set_edge_attr) based on certain criteria. For example, in the code below, I'm trying to double the age attribute of edges with weight = 1.

nodes <- data.frame(name=c('1', '4', '5', '6', '8'))
edges <- data.frame(
    from = c('1', '4', '5', '1', '8', '1'),
    to = c('4', '5', '6', '8', '6', '6'),
    weight = c(1, 1, 1.5, 1.5, 2.5, 5),
    age=c(48, 33, 45, 34, 21, 56)
)
graph = graph_from_data_frame(d = edges, vertices = nodes, directed=FALSE)

edgeseq = E(graph)[[weight==1]]
newage <- edge_attr(graph, "age", index = edgeseq)*2
edge_attr(graph, "age", edgeseq) <- newage
#Alternatively:
set_edge_attr(graph, "age", edgeseq, newage)

However, this throws an error:

Error in `[[<-`(`*tmp*`, index, value = value) : 
attempt to select more than one element in vectorIndex

The error does not occur when I set the attributes without an edge sequence. Any help would be much appreciated!

Upvotes: 0

Views: 714

Answers (1)

desval
desval

Reputation: 2435

The proper way to select edges is:

edgeseq = E(graph)[weight==1]

Note the difference:

E(graph)[weight==1]
+ 2/6 edges from 33d7121 (vertex names):
[1] 1--4 4--5


E(graph)[[weight==1]]
+ 2/6 edges from 33d7121 (vertex names):
  tail head tid hid weight age
1    1    4   1   2      1  96
2    4    5   2   3      1  66

Upvotes: 0

Related Questions