Seanosapien
Seanosapien

Reputation: 450

Populating a vector with a for loop

I am trying to fill a vector pred_pos with the result pred on each iteration of the for loop. However, my pred_pos vector is never filled. The my_vec object is a list of large character vectors which I don't believe needs to be reproduced for this problem as it is most likely a fundamental indexing error. I just need to know how to populate a vector from this for loop. I can't seem to work out a solution.

pred_pos <- vector("numeric" , 2)


for(i in my_vec) { 
        for(r in pred_pos) {
        inserts <- sapply(i, function(n) { n <- cond_probs_neg[n] } ) 
        pred <- sum(unlist(inserts) , na.rm = T) * apriori_neg
        pred_pos[r] <- pred
        } 
      }

Upvotes: 1

Views: 1490

Answers (1)

Phantom Photon
Phantom Photon

Reputation: 808

Assuming that the rest of your code works, there is no need to explicitly state:

pred_pos <- vector("numeric" , 2)

That creates a numeric vector of length two. You ought to be able to write:

pred_pos <- vector()

Now when you wish to append to the vector you can simply use:

vector[length(vector)+1] <- someData

I believe your code should work if it is adjusted:

pred_pos <- vector()

for(i in my_vec) { 
        inserts <- sapply(i, function(n) { n <- cond_probs_neg[n] } ) 
        pred <- sum(unlist(inserts) , na.rm = T) * apriori_neg
        pred_pos[length(pred_pos)+1] <- pred
 }

Upvotes: 2

Related Questions