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 ...