Search code examples
rgraphnodesedges

R: creating a 'statnet' network with node attributes


I am following the examples over here on using the "statnet" library in http://personal.psu.edu/drh20/papers/v24i09.pdf.

The first example shows how to inspect a statnet network object in R:

library(statnet)
library(network)
 data("faux.magnolia.high") 
 fmh <- faux.magnolia.high 
summary(fmh)

In the above example, it seems here that the statnet network in this example already has "node attributes".

Using the statnet library, does anyone know if there is a way to directly create a network with node attributes from a data frame?

For example, if I have some data that looks like this:

mydata <-data.frame(

"source" = c("123","124","123","125","123"),
"target" = c("126", "123", "125", "122", "111"),
"color" = c("red","red","green","blue","red"),
"food" = c("pizza","pizza","cake","pizza","cake")
)

Suppose I had a pre defined list of node attributes:

Nodes <-data.frame(

"source" = c("123","124","125","122","111", "126"),

"Country" = c("usa", "uk", "uk", "usa", "uk", "usa")

)

I tried the following code:

net = network(mydata)

But I am not sure if this has created a network with the node attributes (color and food).

I also tried this, but it did not work:

mydata <-data.frame(

"source" = c("123","124","123","125","123"), "target" = c("126", "123", "125", "122", "111"), "color" = c("red","red","green","blue","red"), "food" = c("pizza","pizza","cake","pizza","cake") )

Nodes <-data.frame(

"source" = c("123","124","125","122","111", "126"),

"Country" = c("usa", "uk", "uk", "usa", "uk", "usa")

)

net<-network(mydata[,c[1:2])

edges <- as.sociomatrix(mydata[,c(3:4)],simplify=TRUE)

nodes <- as.sociomatrix(Nodes,simplify=TRUE)

final <- as.sociomatrix(list(net,edges,nodes))

Can someone please show me how to create a network with node attributes?

source: https://rdrr.io/github/statnet/network/man/as.sociomatrix.html

Thanks


Solution

  • Could this be the answer? https://igraph.org/r/doc/graph_from_data_frame.html

    library(igraph)
    
    g <- graph_from_data_frame(mydata, directed=TRUE, vertices=Nodes)