GenomicRanges: get nearest neighbor distances for random genes using a for loop
Is it because rand.gr has not been initialised, so when you ask to set rand.gr[i] it can't because there isn't one yet?

If you set i to a value (e.g. 1), and run the lines inside your loop, which of the lines produces the error?

If you don't need to retain all the random genomic ranges at the end, you could just leave out some of the [i]s, something like this:

for(i in 1:ncol(rand.df)){
  rand.gr &lt;- gr[(elementMetadata(gr)[,"gene"] %in% rand.df[,i])]
  dists &lt;- distanceToNearest(x = rand.gr)
  output &lt;- print(mcols(dists[,1]))
}