【问题标题】:Suppress function output with markdown使用 markdown 抑制函数输出
【发布时间】:2018-01-29 13:10:32
【问题描述】:

我正在尝试从 R 创建一个降价文档。下面是我的代码。它工作得很好,但是我从tryFun.R获取了一个函数(tryFun())。这个函数的输出我存储在一个变量中。当我这样做时,它还会自动打印输出。但是,我想确定自己在哪里使用该变量的输出,所以稍后我调用它。将结果分配给变量时如何抑制函数的输出?

tryRmd.R 中的代码:

#' ---
#' title: "Try for the first time"
#' output: word_document
#' params: 
#'    xvar: "" 
#' ---

#' ## Introduction 
#' Hi, this is me trying something for the first time 
#' #Hello again 
```{r, echo=FALSE}
plot(1:100)
#x <- 3
source("tryFun.r")
cat("hi")
xvar <- params$xvar 
x1 <- invisible(tryFun(xvar)) 
### shows a plot here (want to suppress this)
cat(x1$res)
plot.new()
x1$p 
### shows the same plot here
```

tryFun.R 中的代码是:

tryFun <- function(x){
    res = 3*x
    plot(1:1000)
    p <- recordPlot()
    return(list(res=res,p=p))
}

我的输出是这样的:

标题

文字

情节 (1:100)

调用x1 &lt;- invisible(tryFun(xvar)) 绘制(1:1000)(这是我不想展示的)

9(来自调用cat(x1$res))

通过调用 x1$p 绘制 (1:1000)

我是这样渲染文档的:

library(rmarkdown)

dire = "D:/"
filename = paste(dire, "tryRmd.r", sep="/")

rmarkdown::render(filename, params=list(xvar=3))

更新

我把代码改成这样:

#' ---
#' title: "Try for the first time"
#' output: word_document
#' params: 
#'    xvar: "" 
#' ---

#' ## Introduction 
#' Hi, this is me trying something for the first time 
#' #Hello again 
```{r, echo=FALSE, results='hide'}
plot(1:100)
direct = "G:/Documents/WarehouseMovements"
filename <- paste(direct, "pickingsregels_wmp700_monthly_201711.txt", sep="/")
#x <- 3
source("tryFun.r")

xvar <- params$xvar 
x1 <- invisible(tryFun(xvar)) 
### shows a plot here (wants to suppress this)
``` 
```{r, echo=FALSE}
cat("hi")
cat(x1$res)
plot.new()
x1$p 
### shows the same plot here
```

但在调用x1 &lt;- invisible(tryFun(xvar)) 时仍会显示情节。

【问题讨论】:

  • 查看块设置中的results = 'hide'
  • 当我更改`{r, echo = FALSE}` into ` {r, echo = FALSE, results='hide'}`时,我仍然得到所有三个图,但 9 (x1$res) 消失了。还有文字“hi”
  • 当然,那是因为它在同一个块中。改变了这一点,但仍然没有用 results='hide' 抑制情节

标签: r function output markdown suppress


【解决方案1】:

我找到了。虽然 results='hide' 什么也没做,但 include=FALSE 做了。

所以我的代码如下所示:

#' ---
#' title: "Try for the first time"
#' output: word_document
#' params: 
#'    xvar: "" 
#' ---

#' ## Introduction 
#' Hi, this is me trying something for the first time 
#' #Hello again 
```{r, echo=FALSE,include=FALSE}
plot(1:100)
direct = "G:/Documents/WarehouseMovements"
filename <- paste(direct, "pickingsregels_wmp700_monthly_201711.txt", sep="/")
#x <- 3
source("tryFun.r")

xvar <- params$xvar 
x1 <- invisible(tryFun(xvar)) 
### shows a plot here (wants to suppress this)
``` 
```{r, echo=FALSE}
cat("hi")
cat(x1$res)
plot.new()
x1$p 
### shows the same plot here
```

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2010-10-03
    • 1970-01-01
    • 2013-10-14
    • 2015-03-06
    • 2019-11-01
    相关资源
    最近更新 更多