For loop iteration

I am writing code to go through each row and if a certain parameter is met, that row will be put into a new table. My code is:

for(i in 1:nrow(mastercourseTable))
if(startsWith(mastercourseTable[i,3], "ACC") == TRUE)
accTable <- mastercourseTable[i,]


It works but will only put the last row that matches the if statement. When I change the action from putting the row into a table to other things like, print(mastercourseTable[i,] it will print each row but as soon as I want them in a table it will not work properly.

It would be easier to help you if you can put your code in reprex (reproducible example).

However, looking at your code I don't see a reason to use for loop in favor of good ol' dplyr::filter. It'll look something like this:

accTable <- mastercourseTable %>%
  dplyr::filter(startsWith(name_of_the_column, "ACC"))

I'm relatively certain it'll work for you and it is much more readable.

Thank you. I am new to R, and I was not aware of this function, which is why I used a for loop. Another question because I am new, the %>% symbol. What does this do or is this just a place holder and I am supposed to swap it out for something?

Never mind, I figured it out. Thank you very much.

1 Like

As a recommendation, I would say that you should take a look at R for Data Science book:

It is a good introduction into R used as a tool for data science.

1 Like