从R保存绘图,然后将其复制到Word文本文件

时间:2014-06-19 14:44:39

标签: r plot

到目前为止我尝试过:

par( mfrow = c( 1, 2 ) )

matplot(rOU,type="l", ylim=range(rOU))
matplot(rEM,type="l", ylim=range(rEM))

1 个答案:

答案 0 :(得分:2)

以下是取自The R Statistics Website

的示例代码

基本上你必须

  • 创建新的Word文件
  • 创建标题和子标题
  • 转到文档中的新页面
  • 撰写文字
  • 插入表格(即“data.frame”和“矩阵”对象)
  • 插入地块
  • 保存并关闭Word文档

代码:

# install.packages("R2wd")
# library(help=R2wd)
require(R2wd)


wdGet(T)    # If no word file is open, it will start a new one - can set if to have the file visiable or not
wdNewDoc("c:\\This.doc")    # this creates a new file with "this.doc" name

wdApplyTemplate("c:\\This.dot") # this applies a template


wdTitle("Examples of R2wd (a package to write Word documents from R)")  # adds a title to the file

wdSection("Example 1 - adding text", newpage = T) # This can also create a header

wdHeading(level = 2, "Header 2")
wdBody("This is the first example we will show")
wdBody("(Notice how, by using two different lines in wdBody, we got two different paragraphs)")
wdBody("(Notice how I can use this: '\ n' (without the space), to  \n  go to the next 
        line)")
wdBody("האם זה עובד בעברית ?")
wdBody("It doesn't work with Hebrew...")
wdBody("O.k, let's move to the next page (and the next example)")

wdSection("Example 2 - adding tables", newpage = T)
wdBody("Table using 'format'")
wdTable(format(head(mtcars)))
wdBody("Table without using 'format'")
wdTable(head(mtcars))


wdSection("Example 3 - adding lm summary", newpage = T)

## Example from  ?lm 
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
group <- gl(2,10,20, labels=c("Ctl","Trt"))
weight <- c(ctl, trt)

# This wouldn't work!
# temp <- summary(lm(weight ~ group))
# wdBody(temp)

# Here is a solution for how to implent the summary.lm output to word
wdBody.anything <- function(output)
{
    # This function takes the output of an object and prints it line by line into the word document
    # Notice that in many cases you will need to change the text font into courier new roman...
    a <- capture.output(output)
    for(i in seq_along(a))
    {
        wdBody(format(a[i]))
    }
}

temp <- summary(lm(weight ~ group))
wdBody.anything(temp)



wdSection("Example 4 - Inserting some plots", newpage = T)

wdPlot(rnorm(100), plotfun = plot, height = 10, width =20, pointsize = 20)
wdPlot(rnorm(100), plotfun = plot, height = 10, width =20, pointsize = 20)
wdPlot(rnorm(100), plotfun = plot, height = 10, width =20, pointsize = 50)

# wdPageBreak()


wdSave("c:\\This.doc") # save current file (can say what file name to use)
wdQuit() # close the word file