下面的最小可重现示例(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)
```
结果可以在这里找到:
最佳答案
我不明白这段代码有什么非线性;也许是因为这个例子(顺便感谢)足够小来演示代码,但又不够大来展示问题。
特别是我不明白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/