Cbrady
Cbrady

Reputation: 93

Looping through rows until criteria is met in R

I'm trying to loop over each row in my dataframe and if that row contains a 1, I'm looking "bf" to change to True so that the loop cancels and then prints out the index of row. Here's the code ive tried below.

bf <- FALSE
for(row in 1:nrow(df)){
   while(bf == FALSE){
      if(df[row, ] == 1){
         bf==TRUE
         print(row)
        
     }
   }
}

However what happens with this code is that it never seems to get if statement and execute it properly to my knowledge

Upvotes: 0

Views: 326

Answers (2)

SteveM
SteveM

Reputation: 2301

You can use the apply, any, which functions to id rows with a 1. Then select the first row:

bdrows <- apply(df, 1, function(x) any(x == 1))
bd <- which(bdrows == TRUE)
firstbdrow <- bd[1]

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388817

bf==TRUE is used for comparison, you might be looking for bf = TRUE. Also this doesn't operation doesn't require for or while loop. Let's say you have a column called column_name in your data you can do :

which.max(df$column_name == 1)

Or

which(df$column_name == 1)[1]

Upvotes: 1

Related Questions