Dr_Watcher
Dr_Watcher

Reputation: 67

Random Iteration Loop in R

I would like to make a for loop that loops through the numbers 1-length(Matrix$Index) in a random order. Note that every number can only be visited once.

How can I achieve this?

Upvotes: 5

Views: 2039

Answers (2)

jrs-x
jrs-x

Reputation: 336

I do not understand your question perfectly, but I guess you try to perform I kind of re-sampling without replacement on your vector, if you want to use R built-in function sample(), then:

n<-10
x<-rnorm(n)
resampled<-sample(x,length(x),replace=F)

Note that I'm using a simulated data (x) from a N(0,1) distribution. If you for any reason want to apply a loop, just try something like:

resampled<-numeric(n)

for(i in 1:n){
              a<-sample(1:n,1)
              resampled[i]<-x[a]
              x<-x[-a]
              n<-n-1
              }

Upvotes: 0

LAP
LAP

Reputation: 6685

for (i in sample(c(1:length(Matrix$Index)))) will achieve this.

You can achieve different samples by changing the seed with set.seed(). Setting a specific seed per sample will allow for reproducability.

Upvotes: 5

Related Questions