GenomicRanges: get nearest neighbor distances for random genes using a for loop I want to compute the nearest neighbour distances using a for loop. I can do this with a random subset by doing this:

df &lt;-  read.table("tmp.txt", header=F)
colnames(df) &lt;- c("gene", "seqnames", "start", "stop", "LOCID")
gr &lt;- makeGRangesFromDataFrame(df, keep.extra.columns=TRUE)

# genes of interest in a list
gene.list &lt;- read.table("careplastic_diffs.txt")

# filters the GenomicRanges object with genes of interest
sub.gr &lt;- gr[(elementMetadata(gr)[, "gene"] %in% gene.list$V1)]

# compute distances
dists &lt;- distanceToNearest(x = sub.gr)

mcols(dists)[,1] # contains a list of distances


I now want to essentially do this 5 times, using the same logic as above:

## create a rand dataframe, each column is a random list of 50 genes
rand.df &lt;- data.frame(replicate(5, sample(gene.list$V1, 50)))

# loop through columns and gets distances and prints to a file
for(i in 1:ncol(rand.df)){
  rand.gr[i] &lt;- gr[(elementMetadata(gr)[,"gene"] %in% rand.df[,i])]
  dists[i] &lt;- distanceToNearest(x = rand.gr[i])
  output &lt;- print(mcols(dists[i][,1]))
}


But I can't seem to make this work.


  Error: subscript contains out-of-bounds indices In addition: Warning
  message: In recycleSingleBracketReplacementValue(value, x, nsbs) :
  number of values supplied is not a sub-multiple of the number of
  values to be replaced


It's probably something really silly but any help would be appreciated ...
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]))
}