Make for loop change after 4 iterations--ie run for loop in sets of four, with separate function in between

Solution 1:

Here's a solution in base R that requires minimal modification to your existing code.

Solution

Within your for loop, simply test your index this.label with the modulo operator %% like so:

for (this.label in seq_len(nrow(data))) {
  if (this.label %% 5 == 0) {
    # example of alternate function for every fourth row of the data frame:
    line <- paste0(data$name[this.label], " is feeling left out!")
  } else {
    # main function I want for every label
    line <- paste0(data$name[this.label], " the ", data$title[this.label], " needs ", data$needs[this.label])
  }
  
  print(line)
}

This test

this.label %% 5 == 0

will evaluate as TRUE every five loops (for this.label ∈ {5, 10, 15, ...}) and so execute the alternate "function" (technically "expression"); whereas the other four loops will simply execute the "main function" (expression).

Result

Given your example code, along with the data in your sample

data <- data.frame(
  title = c("big Cactus", "little cactus", "bad cactus", "skinny cactus", "round cactus", "spiny cactus", "twisty cactus", "bizarre cactus"),
  name = c("Franklin", "Stephanie", "Megan", "Mark", "Patricia", "KD", "Claude", "Audrey"),
  needs = c("nothing", "some love", "too much", "some water", "some sunlight", "new soil", "transplanted", "a friend")
)

this solution should yield the desired output:

[1] "Franklin the big Cactus needs nothing"
[1] "Stephanie the little cactus needs some love"
[1] "Megan the bad cactus needs too much"
[1] "Mark the skinny cactus needs some water"
[1] "Patricia is feeling left out!"
[1] "KD the spiny cactus needs new soil"
[1] "Claude the twisty cactus needs transplanted"
[1] "Audrey the bizarre cactus needs a friend"

Note

I've replaced the clunky 1:dim(data)[1] with seq_len(nrow(data)), which is the proper way to iterate over the rows of a table. In cases where the table is empty (0 rows), this prevents any looping over 1:0 (ie. c(1, 0)) that targets nonexistent rows.

Solution 2:

make_label_A <- function(this.label) {
  line <- paste0(data$name[this.label], " the ", data$title[this.label], " needs ", data$needs[this.label])
  print(line)
}

make_label_B <- function(this.label) {
  line <- paste0(data$name[this.label], " is feeling left out!")
  print(line)
}

for (i in seq(1,dim(data)[1], 5)) {
  sapply(1:4, \(x) make_label_A(i+x))
  make_label_B(i+4)
}

Hope this agrees well with the LaTeX engine you are using. Sometimes print statement require a little more care to show from within loops.