using a loop in write.table

Hello all,
I want to write five different files using a loop in r. My current code is as follows:

write.table(CAR1_final, file = "C:/Users/khalili/Desktop/Newfolder3/CAR1.txt", sep = "",quote = FALSE,row.names = FALSE, col.names = FALSE)
write.table(CAR2_final, file = "C:/Users/khalili/Desktop/Newfolder3/CAR2.txt", sep = "",quote = FALSE,row.names = FALSE, col.names = FALSE)
write.table(CAR3_final, file = "C:/Users/khalili/Desktop/Newfolder3/CAR3.txt", sep = "",quote = FALSE,row.names = FALSE, col.names = FALSE)
write.table(CAR4A_final, file = "C:/Users/khalili/Desktop/Newfolder3/CAR4A.txt", sep = "",quote = FALSE,row.names = FALSE, col.names = FALSE)
write.table(CAR5_final, file = "C:/Users/khalili/Desktop/Newfolder3/CAR5.txt" , sep = "",quote = FALSE,row.names = FALSE, col.names = FALSE)

How can I skip repetition using a loop?
Thanks,

You would be interesting in the purrr :package: and its purrr::walk or purrr::walk2 function.


If you don't know it yet, I would advise to look at the vignette.

You can also use base R with lapply or mapply

all this will allow you to iterate through a list and apply a function. In your case you need a list of object and a list of files.

Try reading the doc and give it a try. If you don't manage to make it work, try post a reprex and we'll help further. There are great ressources on purrr
https://jennybc.github.io/purrr-tutorial/talks.html

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.