user3141121
user3141121

Reputation: 490

breaking an if loop inside a for loop and printing output

I have a dataframe and I would like to loop over it with an if condition.

head(d)
   col1 col2 col3
1   1   1  2.785561
2   2   1  5.765601
3   3   1  1.606134
4   4   1  3.475117
5   5   1  3.352561
6   6   1  2.849907
...
...
...

I would like to sum up each value in the dataframe and if the value gets larger than 10 I want to record the index of the loop and end the loop. I only want to record one number. What I have is:

for (j in 1:nrow(d)){                     
    if (d[j,3] > 10){
      break } 
    output = j }

but the output value ends up being larger than the real answer, which should be 3.

  output
[1] 17

Upvotes: 0

Views: 53

Answers (2)

akrun
akrun

Reputation: 886948

If you want to use the for loop, you could use:

sum1 <- 0
for (j in 1:nrow(d)) {
sum1 <- sum1 + d$col3[j]
if (sum1 > 10) {
    break
  }
output = j + 1
} 

output
#[1] 3

Upvotes: 0

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

A more way to do this would be to use cumsum and which:

which(cumsum(d$col3) > 10)[1]
# [1] 3

Upvotes: 3

Related Questions