0

を使用して開くファイルがありますwdGet(filename="exOut.doc",visible=FALSE)。このファイルには、html と を使用して挿入した画像が既に含まれていますcat(img, file=outputDoc, sep="\n", append=TRUE)

文書の最後に表を挿入する必要がありますがwdTable(format(head(testTable)))、表を Word 文書の最上部に配置します。どうすればこれを修正できますか?

また、2 番目の問題: ドキュメントに挿入する必要があるテーブルがたくさんあるため、ループを使用します。以下は、私の問題を示すサンプル コードです。ここが私にとって本当に奇妙な部分です。コードをステップ実行して各行を次々と実行すると、エラーは発生せず、出力ドキュメントが得られます。すべてを一度に実行すると、「接続エラーを開けません」というメッセージが表示されます。これがどうなるかわかりません。一度に 1 行ずつ実行すると、まったく同じコードをすべて一度に実行するのとは異なる結果が生じる可能性があるのはどうしてでしょうか?

rm(list=ls())

library(R2wd)
library(png)

outputForNow<-"C:\\Users\\dirkh_000\\Downloads\\"
outputDoc<-paste(outputForNow,"exOut.doc",sep="")
setwd(outputForNow)

# Some example plots
for(i in 1:3) 
{ 
  dir.create(file.path(paste("folder",i,sep="")))
  setwd(paste("folder",i,sep="")) # Note that images are all in different folders
  png(paste0("ex", i, ".png"))
  plot(1:5)
  title(paste("plot", i))
  dev.off()
  setwd(outputForNow)
}

setwd(outputForNow)
# Start empty word doc
cat("<body>", file="exOut.doc", sep="\n")

# Retrieve a list of all folders
folders<-dir()[file.info(dir())$isdir]
folders<-folders[!is.na(folders)]

# Cycle through all folders in working directory
for(folder in folders){
  setwd(paste(outputForNow,folder,sep=""))
  # select all png files in working directory
  for(i in list.files(pattern="*.png"))
  {
    temp<-paste0('<img src=','\"',gsub("[\\]","/",folder),"/", i, '\">')
    cat(temp, file=outputDoc, sep="\n", append=TRUE)
    setwd(paste(outputForNow,folder,sep=""))
  }
  setwd(outputForNow)
  cat("</body>", file="exOut.doc", sep="\n", append=TRUE)
  testTable<-as.data.frame(cbind(1,2,3))
  wdGet(filename="exOut.doc",visible=FALSE)
  wdTable(format(head(testTable))) ## This produces a table at the top and not the bottom of the document
  wdSave(outputDoc)
  wdQuit() # NOTE that this means that the document is closed and opened over and over again in the loop otherwise cat() will throw an error
}

上記のコードは以下を生成します。

Error in file(file, ifelse(append, "a", "w")) : 
  cannot open the connection

なぜこれが発生するのか、それを修正する方法を誰か教えてもらえますか? よろしくお願いします。私がこれを間違った方法で行っていることがわかっている場合は、まったく異なるアプローチをお勧めしますが、何が間違っているのかについても説明してください。

4

1 に答える 1