2

I want that the results, which are generated by my for-loop are passed into one single data.frame. Therefore I created one empty data.frame like this:

result <- data.frame(matrix(ncol = 8, nrow = 1))

and then matched the names of the columns with the names of the data.frame, which is going to be searched:

names(result) <- names(example)

My for-loop should iterate through a list of values and check the input data.frame for values that meet the conditions and then add the entire row of this value to my empty data.frame

lpos
[1] 5

for(i in lpos){
indx <- sapply(example[,4], function(x) (x > minpos[i]) & (x < maxpos[i])) 
newrow <- example[indx,]
result = rbind(result, newrow)
}

So my expected output would be that I got a data.frame, containing all results. But it seems that this code overwrites the added rows everytime and I just got the last iteration saved in my data.frame.

What can I do to prevent this code from overwriting the existing results? So my data looks like this:

> head(example[1:4,-9])
      V1       V2   V3    V4    V5   V6 V7 V8
1 Spenn-ch00 AUGUSTUS mRNA  5691  9072 0.84  -  .
2 Spenn-ch00 AUGUSTUS mRNA 11246 12192 0.17  -  .
3 Spenn-ch00 AUGUSTUS mRNA 12799 15702 0.33  -  .
4 Spenn-ch00 AUGUSTUS mRNA 15752 18482 0.48  -  .
JadenBlaine
  • 275
  • 1
  • 3
  • 13
  • Why use `O` within loop, easily misread as `0` zero. – zx8754 May 05 '15 at 08:21
  • Please add output of `head(example)` or `dput(example)` to the post, so we know about your data. Probably you can avoid for loop altogther. – zx8754 May 05 '15 at 08:25
  • [How to make a great R reproducible example?](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – zx8754 May 05 '15 at 08:30
  • 1
    I think you are looking for merge on ranges - see [example on mergeByOverlaps](http://stackoverflow.com/a/29649005/680068) – zx8754 May 05 '15 at 08:35
  • 1
    So I posted the head of my `data.frame`. And yes that looks like it would be the right thing for me to use! – JadenBlaine May 05 '15 at 08:36
  • 1
    Looks like you just have to change to `for(i in 1 : lpos){...` -- or is `lpos` a vector? More details would be helpful. – vaettchen May 05 '15 at 08:48
  • Thanks @vaettchen that was indeed the problem of the code. I have not thought of it just taking the one number. Now it works as it should. – JadenBlaine May 05 '15 at 09:00

1 Answers1

1

The problem was that I just took the one number contained in lpos instead of using the range from 1 to lpos

lpos
[1] 5

for(i in 1:lpos){
indx <- sapply(example[,4], function(x) (x > minpos[i]) & (x < maxpos[i])) 
newrow <- example[indx,]
result = rbind(result, newrow)
}

When the code is like this now, it works perfectly.

JadenBlaine
  • 275
  • 1
  • 3
  • 13