r - 使用knitr生成复杂的动态文档

标签 r knitr modularity r-markdown reproducible-research

下面的最小可重现示例(RE)是我尝试弄清楚如何使用knitr来生成复杂的动态文档,其中这里的“复杂”不是指文档的元素及其布局,而是指底层 R 代码块的非线性逻辑。虽然提供的 RE 及其结果表明基于这种方法的解决方案可能效果很好,但我想知道:1) 这是一个正确的 在这种情况下使用 knitr 的方法; 2) 是否可以进行任何优化来改进该方法; 3) 有哪些替代方法,可以降低代码块的粒度

EDA源代码(文件“reEDA.R”):

## @knitr CleanEnv
rm(list = ls(all.names = TRUE))

## @knitr LoadPackages
library(psych)
library(ggplot2)

## @knitr PrepareData

set.seed(100) # for reproducibility
data(diamonds, package='ggplot2')  # use built-in data


## @knitr PerformEDA

generatePlot <- function (df, colName) {

  df <- df
  df$var <- df[[colName]]

  g <- ggplot(data.frame(df)) +
    scale_fill_continuous("Density", low="#56B1F7", high="#132B43") +
    scale_x_log10("Diamond Price [log10]") +
    scale_y_continuous("Density") +
    geom_histogram(aes(x = var, y = ..density..,
                       fill = ..density..),
                   binwidth = 0.01)
  return (g)
}

performEDA <- function (data) {

  d_var <- paste0("d_", deparse(substitute(data)))
  assign(d_var, describe(data), envir = .GlobalEnv)

  for (colName in names(data)) {
    if (is.numeric(data[[colName]]) || is.factor(data[[colName]])) {
      t_var <- paste0("t_", colName)
      assign(t_var, summary(data[[colName]]), envir = .GlobalEnv)

      g_var <- paste0("g_", colName)
      assign(g_var, generatePlot(data, colName), envir = .GlobalEnv)
    }
  }
}

performEDA(diamonds)

EDA 报告 R Markdown 文档(文件“reEDA.Rmd”):

```{r KnitrSetup, echo=FALSE, include=FALSE}
library(knitr)
opts_knit$set(progress = TRUE, verbose = TRUE)
opts_chunk$set(
  echo = FALSE,
  include = FALSE,
  tidy = FALSE,
  warning = FALSE,
  comment=NA
)
```

```{r ReadChunksEDA, cache=FALSE}
read_chunk('reEDA.R')
```

```{r CleanEnv}
```

```{r LoadPackages}
```

```{r PrepareData}
```

Narrative: Data description

```{r PerformEDA}
```

Narrative: Intro to EDA results

Let's look at summary descriptive statistics for our dataset

```{r DescriptiveDataset, include=TRUE}
print(d_diamonds)
```

Now, let's examine each variable of interest individually.

Varible Price is ... Decriptive statistics for 'Price':

```{r DescriptivePrice, include=TRUE}
print(t_price)
```

Finally, let's examine price distribution across the dataset visually:

```{r VisualPrice, include=TRUE, fig.align='center'}
print(g_price)
```

结果可以在这里找到:

http://rpubs.com/abrpubs/eda1

最佳答案

我不明白这段代码有什么非线性;也许是因为这个例子(顺便感谢)足够小来演示代码,但又不够大来展示问题。

特别是我不明白performEDA函数的原因。为什么不将该功能放入 Markdown 中?读起来似乎更简单、更清晰。 (这未经测试...)

Let's look at summary descriptive statistics for our dataset

```{r DescriptiveDataset, include=TRUE}
print(describe(diamonds))
```

Now, let's examine each variable of interest individually.

Varible Price is ... Decriptive statistics for 'Price':

```{r DescriptivePrice, include=TRUE}
print(summary(data[["Price"]]))
```

Finally, let's examine price distribution across the dataset visually:

```{r VisualPrice, include=TRUE, fig.align='center'}
print(generatePlot(data, "Price"))
```

看起来您要显示所有变量的图;您是否想在那里循环?

此外,这不会改变功能,但在 R 习惯用法中,让 performEDA 返回一个包含其创建的内容的列表,而不是分配到全局环境中,这会更符合 R 习惯用法。我花了一段时间才弄清楚代码的作用,因为这些新变量似乎没有在任何地方定义。

关于r - 使用knitr生成复杂的动态文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25715609/

相关文章:

r - Knitr 提供与 RStudio 不同的结果

Javascript requirejs 在开发中但在生产中编译

javascript - 'var webApp = { .. }'和 'var webApp = function (){ .. }'有什么区别

r - 如何使用右/左拆分sqldf中的变量,如左(x,n)

在 R 中使用 "relational"数据帧重命名列

r - knit 与 gganimate,找不到 ffmpeg 命令

c++ - Lua 和 C++ : separation of duties

r - boxplot ggplot2::qplot() 在同一图中 R 中未分组和分组的数据

r - 将单个数据框转换为数据框列表(将列名解析为前缀和后缀)

plot - 在 R Markdown/knitr 中缩略图一些图的简单方法是什么?