misterE
misterE

Reputation: 93

For loop and 'which' command

So I'm currently trying to get a random initial pathway between nodes. I've tried the following code, but at times it 'skips' a node i,e sometimes the same node is visited twice rather than it traversing each one. But since I've defined a visited node's 'column' as all 0 I don't see why this should happen when using the which(>0) command. Any advice?

A<-matrix(sample(1:15,25,replace=TRUE), ncol=5) 

n=nrow(A)

b=c()
a=c(1:nrow(A))
b[1]=sample(a,1)

for(i in 2:n){
A[,b[i-1]]<-rep(0,n)
d=which(A[b[i-1],]>0)
b[i]=sample(d,1)
}

print(b)

Upvotes: 1

Views: 62

Answers (1)

MrFlick
MrFlick

Reputation: 206401

The problem is that sample behaves differently when you pass it a vector of length 1. Observe

set.seed(14)
x<-c(5,3)
sample(x, 1)
# [1] 5
x<-5
sample(x, 1)
# [1] 4

you see that sample returned 4. When you pass in a vector of length one, it draws from 1:x. You can write your own wrapper if you like

Sample<-function(x,n ) {
    if(length(x)>1) 
         sample(x,n)
    else if (length(x)==1 & n==1) {
         x
    } else {
        stop("error")
    }
}

and then use this function instead.

But it seems like you are just shuffling your rows. Why not just permute the index with one call to sample:

sample(seq_len(nrow(A))

Upvotes: 4

Related Questions