JadenBlaine
JadenBlaine

Reputation: 275

Let a for loop add all results to an existing data.frame

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

Upvotes: 2

Views: 3015

Answers (1)

JadenBlaine
JadenBlaine

Reputation: 275

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.

Upvotes: 1

Related Questions