Sorting nodes by degree and manipulating in R using igraph
The datasets I'm working with show links between nodes. For example:
> data2
V1 V2
1 10000 4725
2 4725 6805
3 4725 3250
4 5725 3250
5 1725 7673
(For example, using a small data set). If the dataframe specifies an undirected connection between node 10000 and 4725, there is a link between node 4725 and 6805, etc. Using the igraph package, I am getting degrees for individual nodes:
g<-graph.data.frame(data2, directed=F)
deg <- igraph::degree(g)
> deg
10000 4725 5725 1725 6805 3250 7673
1 3 1 1 1 2 1
Then I sort the nodes according to their degrees in descending order:
> dSorted <-sort.int(deg,decreasing=TRUE,index.return=FALSE)
> dSorted
4725 3250 10000 5725 1725 6805 7673
3 2 1 1 1 1 1
Taking the first column of the dataframe:
> ln1 <- data2[,1]
> ln1
[1] 10000 4725 4725 5725 1725
My goal is to replace the nodes in ln1 with the corresponding orders of the nodes in dSorted. For example, 10000 should be replaced with 3 because dSorted 10000 is in the 3rd index. Likewise, 4725 should be replaced with 1 as it comes first in dSorted. I've tried the following code:
> for(i in 1:length(deg)){ln1[which(ln1==dSorted[i])]<-i}
But it doesn't work. ln1 remains the same. It occurred to me that in dSorted, node numbers are treated as indices. So I also tried the following code (dSorted returns an index vector):
> dSorted <- sort.int(deg,decreasing=TRUE,index.return=TRUE)
> for(i in 1:length(deg)){ln1[which(ln1==dSorted$ix[i])]<-i}
But ln1 is still the same. I'm very new to R. Would really appreciate if someone kindly shows me the way here.
source to share
If you understand correctly, you can do:
ln1 <- order(order(deg, decreasing=T))
# [1] 3 1 4 5 6 2 7
# if you want names
names(ln1) <- names(deg)
# 10000 4725 5725 1725 6805 3250 7673
# 3 1 4 5 6 2 7
So, as mentioned, 10000 has a value of 3 because it is 3rd in the order 4725 has a value of 1 because it is 1st in an order, etc.
Way sort
and order
related: sort
by default sorts your vector, but order
returns the indices that sort your vector.
Why double- order
? they are inverse to each other.
sorted <- sort(deg)
deg[order(deg)] == sorted
sorted[order(order(deg))] == deg
order(deg)
will place the unsorted deg
so it's okay.
order(order(deg))
will order your sorted deg
to resemble the original order. Confusing in words, but play with it and you will see.
source to share