Answers.Body: <p>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?</p>
  
  <p>If you set i to a value (e.g. 1), and run the lines inside your loop, which of the lines produces the error?</p>
  
  <p>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:</p>
  
  <pre><code>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]))
  }
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2019-11-08T12:38:31.643Z
Answers.Text: Isn't `output` being overwritten with each iteration?
Answers.UserDisplayName: haci
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2019-11-08T13:17:33.080Z
Answers.Text: Thanks, I do need a file with essentially columns of distance data (each column corresponding to a column in rand.df)
Answers.UserDisplayName: R-MASHup
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2019-11-08T13:23:18.570Z
Answers.Text: this seemed to create another problem: https://www.dropbox.com/s/jl03i9nm87vwbxz/Screenshot%202019-11-08%20at%2013.21.04.png?dl=0
Answers.UserDisplayName: R-MASHup
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2019-11-12T10:38:51.643Z
Answers.Text: haci is correct, ouput is overwritten on each time round the loop.
Answers.UserDisplayName: Jay Moore
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2019-11-08T11:47:10.547Z
Answers.LastActivityDate: 2019-11-08T12:17:14.480Z
Answers.LastEditDate: 2019-11-08T12:17:14.480Z
Answers.UserDisplayName: Jay Moore
Answers.Body: <p>You could do this much more easily and much faster on the command line, starting with an unsorted BED file of genes called <code>genes.unsorted.bed</code>:</p>
  
  <pre><code>$ sort-bed genes.unsorted.bed | shuf - | head -5 - | sort-bed - | closest-features --closest --dist --no-overlaps - &gt; answer.bed
  </code></pre>
  
  <p>Replace the <code>5</code> in <code>head -5</code> with however many random genes you want. Remove <code>--no-overlaps</code> if you want to allow consideration of overlapping genes (which returns a distance of zero).</p>
  
  <p>Output columns are delimited with <code>|</code>. This can be replaced with another delimiter, but the output can be brought into R easily with <code>read.table</code> or similar.</p>
  
  <p>Ref: <a href="https://bedops.readthedocs.io/en/latest/content/reference/set-operations/closest-features.html" rel="nofollow noreferrer">https://bedops.readthedocs.io/en/latest/content/reference/set-operations/closest-features.html</a></p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2019-11-15T23:08:15.010Z
Answers.Text: i thought closest-features requires a reference and an input file?
Answers.UserDisplayName: R-MASHup
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2019-11-12T23:29:49.513Z
Answers.LastActivityDate: 2019-11-12T23:29:49.513Z
Answers.UserDisplayName: Alex Reynolds
Body: <p>I want to compute the nearest neighbour distances using a for loop. I can do this with a random subset by doing this:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I now want to essentially do this 5 times, using the same logic as above:</p>
  
  <pre><code>## 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]))
  }
  </code></pre>
  
  <p>But I can't seem to make this work.</p>
  
  <blockquote>
    <p>Error: subscript contains out-of-bounds indices In addition: Warning
    message: In recycleSingleBracketReplacementValue(value, x, nsbs) :<br>
    number of values supplied is not a sub-multiple of the number of
    values to be replaced</p>
  </blockquote>
  
  <p>It's probably something really silly but any help would be appreciated ... </p>
  
Tags: <r><bioconductor><genomicranges><genomefeatures>
Title: GenomicRanges: get nearest neighbor distances for random genes using a for loop
ThreadText: # GenomicRanges: get nearest neighbor distances for random genes using a for loop
  
  (Asked by: username_0 on 2019-11-08)
  
  I want to compute the nearest neighbour distances using a for loop. I can do this with a random subset by doing this:
  
  ```
  df <-  read.table("tmp.txt", header=F)
  colnames(df) <- c("gene", "seqnames", "start", "stop", "LOCID")
  gr <- makeGRangesFromDataFrame(df, keep.extra.columns=TRUE)
  
  # genes of interest in a list
  gene.list <- read.table("careplastic_diffs.txt")
  
  # filters the GenomicRanges object with genes of interest
  sub.gr <- gr[(elementMetadata(gr)[, "gene"] %in% gene.list$V1)]
  
  # compute distances
  dists <- 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 <- 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] <- gr[(elementMetadata(gr)[,"gene"] %in% rand.df[,i])]
    dists[i] <- distanceToNearest(x = rand.gr[i])
    output <- 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 ...
  
  **Tags:** r, bioconductor, genomicranges, genomefeatures
  
  
  ---
  
  ## 2 answers
  
  ### Answer by username_1 on 2019-11-08. Score: 1 | Accepted answer
  
  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 <- gr[(elementMetadata(gr)[,"gene"] %in% rand.df[,i])]
    dists <- distanceToNearest(x = rand.gr)
    output <- print(mcols(dists[,1]))
  }
  
  ```
  
  > **Comments:**
  > **username_2**: Isn't `output` being overwritten with each iteration?  
  > **username_0**: Thanks, I do need a file with essentially columns of distance data (each column corresponding to a column in rand.df)  
  > **username_0**: this seemed to create another problem: https://www.dropbox.com/s/jl03i9nm87vwbxz/Screenshot%202019-11-08%20at%2013.21.04.png?dl=0  
  > **username_1**: username_2 is correct, ouput is overwritten on each time round the loop.  
  
  ---
  
  ### Answer by username_3 on 2019-11-12. Score: 0
  
  You could do this much more easily and much faster on the command line, starting with an unsorted BED file of genes called `genes.unsorted.bed`:
  
  ```
  $ sort-bed genes.unsorted.bed | shuf - | head -5 - | sort-bed - | closest-features --closest --dist --no-overlaps - > answer.bed
  
  ```
  
  Replace the `5` in `head -5` with however many random genes you want. Remove `--no-overlaps` if you want to allow consideration of overlapping genes (which returns a distance of zero).
  
  Output columns are delimited with `|`. This can be replaced with another delimiter, but the output can be brought into R easily with `read.table` or similar.
  
  Ref: <https://bedops.readthedocs.io/en/latest/content/reference/set-operations/closest-features.html>
  
  > **Comments:**
  > **username_0**: i thought closest-features requires a reference and an input file?  
  
  ---
  
  