user7148318 user7148318 - 23 days ago 6
R Question

A loop routine in R

Suppose, I have written 6 functions defined as objects named A, B,...F in R.

Now, I want the below package to run 6 times, each time putting one of the 6 functions' names, say, A, in front of "fun=" and putting a file name in front of "file=". File names may be 1.docx for A, 2.docx for B,..., 6.docx for F.

Here is the package I want to run 6 times (note that at each run, only "fun=" & "file=" need to change):

library('ReporteRs')
doc = docx()
doc = addPlot(doc, fun = A, vector.graphic = TRUE)
writeDoc(doc, file = "1.docx")

Answer

Consider a simple lapply using seq_along for number iteration:

funclist <- list(A, B, C)

lapply(seq_along(funclist), function(i){
   doc = docx()
   doc = addPlot(doc, fun = funclist[[i]], vector.graphic = TRUE) 
   writeDoc(doc, file = paste0(i, ".docx"))
})
Comments