get.inducedSubgraph isolated alters

2019-08-26 21:45发布

问题:

I have a list containing 3,000 networks. For each of them I need to calculate the density among alters whose attribute "att"==1. I have tried several options, and here is my final code (I am just experimenting with 3 networks). The main problem is that some networks do not containing any alter for which "att"==1. Since get.inducedSubgraph don't work for these cases, I am trying to eliminate them. However, I still get an error message. Trying different options it seems to me that the message appears when I have just two alters in the network and there are not linked to each other (density = 0). Is that possible? Otherwise, which error am I making?

m1 <- matrix(rbinom(25,1,.4),5,5)
diag(m1) <- 0
g1 <- network(m1)
set.vertex.attribute(g1,"att",as.character(rep(0:1,dim(m1)[1])))

m2 <- matrix(rbinom(36,1,.4),6,6)
diag(m2) <- 0
g2 <- network(m2)
set.vertex.attribute(g2,"att",as.character(rep(0:1,dim(m2)[1])))

m3 <- matrix(rbinom(36,1,.4),6,6)
diag(m3) <- 0
g3 <- network(m3)
set.vertex.attribute(g3,"att",as.character(rep(0,dim(m2)[1]))) 

net.list=list(g1,g2,g3)

size=vector()
for(i in 1:length(net.list))
size[[i]]=sum(get.vertex.attribute(net.list[[i]], "att")=="1")
size
[1] 2 3 0

density=vector()
for(i in 1:length(net.list))
density[[i]]=ifelse(size[[i]]>1, gden(get.inducedSubgraph(net.list[[i]],v=which(net.list[[i]]%v%"att"=="1"))), NA)

Error in `[<-`(`*tmp*`, nal, 3, value = NA) : subscript out of bounds

回答1:

it looks like the problem is that you create your size and density variables as vectors, and then try to index them using list notation [[]] instead of vector notation []

changing your code as follows worked for me:

size=vector()
for(i in 1:length(net.list))
size[i]=sum(get.vertex.attribute(net.list[[i]], "att")=="1")
size
[1] 2 3 0

density=vector()
for(i in 1:length(net.list))
density[i]=ifelse(size[i]>1, gden(get.inducedSubgraph(net.list[[i]],v=which(net.list[[i]]%v%"att"=="1"))), NA)

FYI, if you are doing this for thousands of networks, might be more efficient to use lapply or sapply syntax instead of a for loop. i.e.

size<-sapply(seq_along(net.list),function(i){
  sum(get.vertex.attribute(net.list[[i]], "att")=="1")}
)


标签: r statnet