Reputation: 760
I need to do something like the following:
Start of code
Repetitive code line 1
Repetitive code line 2
Repetitive code line 3
......
Repetitive code line n
End of code
So far I've tried putting a for-loop into a print statement:
strings2<-c("a","b","c","d","e","f","g")
print(paste("start of code",for(i in strings2){print(paste0("repetitive code line",i))},"end of code"))
However, the "Start of code" and "end of code"-lines turns up at the wrong place:
[1] "repetitive code linea"
[1] "repetitive code lineb"
[1] "repetitive code linec"
[1] "repetitive code lined"
[1] "repetitive code linee"
[1] "repetitive code linef"
[1] "repetitive code lineg"
[1] "start of code end of code"
Can this be done with a for-loop, or is there a better way?
Upvotes: 0
Views: 58
Reputation: 1595
This does what you are asking but I am not sure it is exactly what you want. For instance, I explicitly coded the starting and ending of the loop. Have a look.
starting <- "start of code"
strings2 <- c("a","b","c","d","e","f","g")
ending <- "end of code"
for (i in seq_along(strings2) ) {
if (i == 1L) {
print(starting)
}
print(strings2[i])
if (i == length(strings2)) {
print(ending)
}
}
#> [1] "start of code"
#> [1] "a"
#> [1] "b"
#> [1] "c"
#> [1] "d"
#> [1] "e"
#> [1] "f"
#> [1] "g"
#> [1] "end of code"
Created on 2022-10-03 with reprex v2.0.2
Upvotes: 1