Doubt with loops

Welcome to the RStudio Community boards!

Unlike SAS, R doesn't have a macro language. Instead, everything is an object that can be created, modified, and referenced. All strings are actually character vectors. Even "C:/Users/yurip/Documents/tablename.txt" is a character vector; it just has one element.

So you can make a character vector with 7 elements, each of which is a name for an output file. For example:

outfiles <- paste0("C:/Users/yurip/Documents/tablename", 1:7, ".txt")
print(outfiles)
# [1] "C:/Users/yurip/Documents/tablename1.txt" "C:/Users/yurip/Documents/tablename2.txt"
# [3] "C:/Users/yurip/Documents/tablename3.txt" "C:/Users/yurip/Documents/tablename4.txt"
# [5] "C:/Users/yurip/Documents/tablename5.txt" "C:/Users/yurip/Documents/tablename6.txt"
# [7] "C:/Users/yurip/Documents/tablename7.txt"

for (i in 1:7) {
  data_f <- x %>%
    filter(Rating_Ini_num == i) %>%
    select(Prazo, PD, Rating_num = Rating_Ini_num)
  p <- approx(data_f$Prazo, data_f$PD, n = 120)
  exp <- data.frame(Prazo = p[1], PD = p[2])
  # Use the i-th value of outfiles for the filepath
  write.table(exp, outfiles[i])
}

Note: I cleaned up the inner loop code. I assume k was supposed to be exp.

Also, we ask posters here to take care that code is properly formatted. It's common for new users to not even know it's possible, let alone how it's done. But it makes the site easier to read, prevents confusion (unformatted code can mistakenly trigger other types of automatic formatting) and generally is considered the polite thing to do. You can read all the details of how to do it here: FAQ: How to format your code

Or try the easy way :grin: : select any code (whether in blocks or in bits and pieces mixed into your sentences) and click the little </> button at the top of the posting box.

2 Likes