Reputation: 51
I have created a network and would be interested in having the nodes possess attributes based on my initial dataframe
. For example, my dataframe
shows that each node as a certain amount of keywords but this is an information that I lost during the process of creating my network. At this stage I would be interested in having it attributed to each node for further analysis at a later stage.
Example of a graph:
g <- graph.formula(4506-8974, 8974-6345, 7842-4653, 4653-6345, 7842-8974)
V(g)$name <- c("4506", "8974", "6345", "7842", "4653")
The additional difficulty is that my dataframe
takes the form of a matrix
(although still technically a dataframe
). The rows are nodes and the columns are keywords. I would like the columns (i.e. keywords) to become an attribute to each node: V(g)$keyword
. If element = 1, than display as attribute, if element = 0, than don't take into account.
Anyone knows how to do it? Should I use an ifelse
function? Furthermore, I think it is important not to mix up the order of the nodes ID since otherwise it might give the keyword attribute to the wrong node.
df <- data.frame("agriculture" = c(0,1,0,0,0), "arts" = c(0,0,0,1,0), "banks" = c(1,0,1,0,0),
"cities" = c(0,0,0,1,0), "companies" = c(0,0,0,0,1))
rownames(df) <- c("4506", "8974", "6345", "7842", "4653")
NodeID agriculture arts banks cities companies
4506 0 0 1 0 0
8974 1 0 0 0 0
6345 0 0 1 0 0
7842 0 1 0 1 0
4653 0 0 0 0 1
V(g)$keyword <- keyword based on if the element = 1 for each node
The result I'm hoping for would be for example:
V(g)$keyword[1]
[1] "banks"
V(g)$keyword[4]
[4] "arts" "cities"
Upvotes: 1
Views: 763
Reputation: 76402
The following code does almost what you want. The difference is that V(g)$keyword
becomes a "list"
. Extraction of its members will therefore be slightly different than your posted example.
V(g)$keyword <- apply(df, 1, function(x) names(df)[x == 1])
V(g)$keyword[1]
#[[1]]
#[1] "banks
V(g)$keyword[[1]]
#[1] "banks"
V(g)$keyword[4]
#[[1]]
#[1] "arts" "cities"
V(g)$keyword[[4]]
#[1] "arts" "cities"
Upvotes: 1