0

I was try to draw a network or connection in R studio. I found an useful package and the information as follows, http://stats.idre.ucla.edu/r/faq/how-can-i-manage-and-plot-social-network-data/

The post started with a data table. The format is as follows,

  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20
1  0  0  1  0  0  1  0  0  0   1   0   0   0   0   0   0   0   0   0   0
2  0  0  0  0  1  1  0  0  0   1   0   0   0   0   0   0   0   0   0   1
3  0  1  0  0  1  0  1  1  0   0   0   0   0   0   0   0   0   1   0   0

Here is my question, my data starts with pairs.

V1;V22 
V1;V24 
V2;V5  
V2;V6  
V2;V10 
V2;V20 
V2;V21 
V3;V2  
V3;V5  
V3;V7

Is there a way to format it into a data table or matrix in R like the first one ? The direction information does not matter.

user3631848
  • 433
  • 1
  • 6
  • 14
  • [Looks similar to this question.](http://stackoverflow.com/questions/16584948/how-to-create-weighted-adjacency-list-matrix-from-edge-list) – Feng Mar 12 '17 at 07:10
  • `igraph` will accept an edgelist when reading in a graph. Converting from that to a matrix will simply cost you RAM... I'm not sure if this is what you meant by your new answer, but if so, I think you'd be justified in accepting it instead of the other one. By the way, relying heavily on links is usually discouraged here (since Q&A is supposed to be useful long into the future but external links are bound to break). – Frank Mar 13 '17 at 16:07
  • Sorry, I'm not quite familiar with R. My original purpose was to plot the network. However, one advantage for the matrix is to calculate the closeness, betweenness, etc. So, I would like to keep both. Thank you for the reminder. I will edit my answer. – user3631848 Mar 15 '17 at 09:50

2 Answers2

1

There's probably a way to do this without a for loop but this should get the job done. Assumes you can ignore the "V" in front of all your numbers.

library(data.table)

#initilize sample data set
DT <- data.table(c(1,1,2,2,2,2,2,3,3,3), c(22,24,5,6,10,20,21,2,5,7))

#Create DT with correct number of rows
DT_1 <- data.table(1:max(DT$V1))

#Add in correct amount of columns
DT_1 <- DT_1[, paste0(1:max(DT)) := .SD][, 2:(max(DT)+1)]

#Set everything to 0
DT_1[,] <- 0

#loop through and add 1 for each reference in the pairs
for(i in 1:dim(DT)[1]){
  DT_1[DT$V1[i], DT$V2[i]] <- DT_1[[DT$V1[i], DT$V2[i]]] + 1
}

#Output
DT_1
coomie
  • 411
  • 4
  • 14
0

I found a post related to the question with the same purpose. https://lists.nongnu.org/archive/html/igraph-help/2008-09/msg00007.html

It shows non-numeric vertex could be read directly and plot by igraph R package.

g <- read.graph("temp.txt", format="ncol")
plot.igraph(g)

The file temp.txt

V1 V22
V1 V24
V2 V5
V2 V6
V2 V10
V2 V20
V2 V21
V3 V2
V3 V5
V3 V7
user3631848
  • 433
  • 1
  • 6
  • 14