user7148318 user7148318 - 1 year ago 89
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):

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

Answer Source

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"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download