Gathering column names from data frame into a list in R

664 views Asked by At

so I have a working data frame right now, but I would like to study the origins of the subjects of the data frame. Here is some of the code I used to create the data frame:

df <- as.data.frame(t(test)) #This is so the row names are products
    vertices <- row.names(df)
    place <- colnames(df)
    L <- length(vertices)
    numedges <- choose(L,2)
    edges <- data.frame(v1=rep(NA, numedges), v2=NA, numrows=NA, location=NA)
    k <- 0
    for(i in 1:(L-1)) {
    for(j in (i+1):L) {
      k <- k + 1
      edges$v1[k] <- vertices[i]
      edges$v2[k] <- vertices[j]
      edges$numrows[k] <- sum(df[vertices[i], ]=="Yes" & df[vertices[j], ]=="Yes")
      edges$location[k] ### Here is my problem!!!
    }}

And I would like the output to look something like:

edges
          v1                    v2     numrows location #What I would like to see
1        Fish                 Squid       8    Town 1, Town 2, Town 4 
2        Fish                Fruits       0    Town 1
3        Fish                  Wood       0    Town 1
4        Fish                   Etc       2    Town 1, Town 2
5        Fish                  Corn       1    Town 1

I think numrows becomes the sum of all the edges? Please correct me if I'm wrong. So then I wanted to gather all the locations where the numrow function was satisfied.

1

There are 1 answers

3
agstudy On

The question is unclear. You don't know how to add an attribute to a graph edge? For example to add an attribute location you simply do this:

E(g)$location=colnames(df)  ## g is your graph

You can check this using

get.edge.attribute(g, 'location')

For example, I can use the attribute location to set the label of edge.

library(igraph)
g <- graph.ring(5)
V(g)$size <- 5
E(g)$location=paste(letters[1:5],LETTERS[1:5],sep=':')
E(g)$label <- get.edge.attribute(g, 'location') 
E(g)$label.cex <- 2
plot(g)

enter image description here