📚 今日目標
- 掌握R Markdown的基本語法和結構
- 學習在報告中嵌入代碼、表格和圖形
- 掌握報告格式化和定製技巧
- 學習生成HTML、PDF、Word等多種格式報告
- 創建交互式報告和儀表板
📝 第一部分:R Markdown基礎
1.1 R Markdown簡介與安裝
# R Markdown是什麼?
# - 將R代碼、結果和文本結合在一個文檔中
# - 支持多種輸出格式(HTML、PDF、Word等)
# - 支持動態內容生成
# 安裝必要的包
install.packages(c("rmarkdown", "knitr", "tinytex"))
# 驗證安裝
library(rmarkdown)
library(knitr)
# 安裝TinyTeX用於PDF輸出
if (!requireNamespace("tinytex", quietly = TRUE)) {
install.packages("tinytex")
tinytex::install_tinytex()
}
1.2 創建第一個R Markdown文檔
# 在RStudio中創建R Markdown文檔:
# 1. File → New File → R Markdown
# 2. 選擇文檔類型(HTML/PDF/Word)
# 3. 填寫標題和作者
# 4. 點擊"OK"
# 或者使用代碼創建模板:
rmarkdown::draft(
file = "my_report.Rmd",
template = "html_document",
package = "rmarkdown",
create_dir = TRUE,
edit = FALSE
)
# 查看模板文件結構
file.edit("my_report/my_report.Rmd")
1.3 R Markdown基本語法
# 這是一個示例R Markdown文檔的基本結構
---
title: "我的數據分析報告"
author: "你的名字"
date: "`r Sys.Date()`"
output: html_document
---
## 一級標題
### 二級標題
#### 三級標題
**粗體文本** 和 *斜體文本*
`行內代碼`
---
1. 有序列表項1
2. 有序列表項2
3. 有序列表項3
- 無序列表項1
- 無序列表項2
- 無序列表項3
[鏈接文本](https://www.example.com)

> 引用文本
---
表格示例:
| 列1標題 | 列2標題 | 列3標題 |
|---------|---------|---------|
| 單元格1 | 單元格2 | 單元格3 |
| 單元格4 | 單元格5 | 單元格6 |
---
數學公式:
行內公式:$E = mc^2$
塊級公式:
$$
f(x) = \frac{1}{\sqrt{2\pi\sigma^2}} e^{-\frac{(x-\mu)^2}{2\sigma^2}}
$$
💻 第二部分:在報告中嵌入R代碼
2.1 代碼塊基礎
# 基本代碼塊語法
```{r}
# 這是一個R代碼塊
x <- 1:10
y <- x^2
plot(x, y, main = "簡單散點圖")
```
# 帶參數的代碼塊
```{r, echo=TRUE, eval=TRUE, warning=FALSE, message=FALSE}
# echo: 是否顯示代碼
# eval: 是否執行代碼
# warning: 是否顯示警告
# message: 是否顯示消息
# results: 輸出方式 ('hide', 'asis', 'hold')
# fig.width, fig.height: 圖形尺寸
```
# 命名代碼塊(便於交叉引用)
```{r data_preparation}
# 數據準備代碼
data <- mtcars
summary(data)
```
2.2 代碼塊選項詳解
# 在R中查看所有可用的代碼塊選項
names(knitr::opts_chunk$get())
# 常用代碼塊選項示例:
#
# 基本控制:
# - echo: TRUE/FALSE - 顯示/隱藏代碼
# - eval: TRUE/FALSE - 執行/不執行代碼
# - include: TRUE/FALSE - 包含/排除整個代碼塊
#
# 結果輸出:
# - results: 'markup', 'asis', 'hold', 'hide'
# - collapse: TRUE/FALSE - 合併輸出
#
# 圖形設置:
# - fig.width: 圖形寬度(英寸)
# - fig.height: 圖形高度(英寸)
# - fig.align: 'left', 'center', 'right'
# - out.width: '70%' (相對大小)
# - out.height: '400px' (絕對大小)
#
# 緩存:
# - cache: TRUE/FALSE - 啓用/禁用緩存
# - cache.path: 緩存路徑
# - dependson: 依賴的代碼塊
#
# 表格輸出:
# - comment: 註釋字符(默認'##')
# - highlight: TRUE/FALSE - 語法高亮
2.3 內聯R代碼
# 在文本中嵌入R代碼
數據集包含 `r nrow(mtcars)` 行和 `r ncol(mtcars)` 列。
平均油耗為 `r mean(mtcars$mpg) %>% round(2)` 英里/加侖。
當前日期是 `r Sys.Date()`。
# 條件文本
`r if (mean(mtcars$mpg) > 20) "平均油耗良好" else "需要改進"`
# 循環生成文本
`r paste0("車型包括:", paste(unique(mtcars$cyl), collapse = ", "))`
# 格式化數字
`r sprintf("平均值為 %.2f,標準差為 %.3f",
mean(mtcars$mpg),
sd(mtcars$mpg))`
📊 第三部分:表格與圖形
3.1 創建美觀的表格
# 使用knitr::kable創建表格
```{r, results='asis'}
library(knitr)
library(dplyr)
# 簡單表格
kable(head(mtcars),
caption = "汽車數據示例")
# 更美觀的表格
kable(mtcars %>%
group_by(cyl) %>%
summarize(
count = n(),
avg_mpg = mean(mpg) %>% round(2),
avg_hp = mean(hp) %>% round(1)
),
caption = "按氣缸數分組彙總",
align = c('l', 'c', 'c', 'c'),
col.names = c("氣缸數", "數量", "平均MPG", "平均馬力"))
```
3.2 使用kableExtra美化表格
```{r}
# 安裝並加載kableExtra
# install.packages("kableExtra")
library(kableExtra)
library(dplyr)
# 創建高度可定製的表格
mtcars %>%
head() %>%
kable(format = "html",
caption = "美化表格示例") %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed"),
full_width = FALSE,
position = "center"
) %>%
row_spec(0, bold = TRUE, color = "white", background = "#4ECDC4") %>%
column_spec(1, bold = TRUE) %>%
add_header_above(c(" " = 1, "性能指標" = 2, "外觀尺寸" = 2)) %>%
footnote(
general = "數據來源: 1974年Motor Trend雜誌",
number = "MPG: 英里/加侖"
)
```
3.3 DT交互式表格
```{r}
# 創建交互式表格
# install.packages("DT")
library(DT)
datatable(
mtcars,
caption = "交互式汽車數據表",
filter = "top", # 頂部過濾器
extensions = c('Buttons', 'ColReorder'),
options = list(
pageLength = 10,
dom = 'Bfrtip',
buttons = c('copy', 'csv', 'excel', 'pdf', 'print'),
colReorder = TRUE,
scrollX = TRUE
)
)
```
3.4 圖形嵌入與格式化
```{r cars-plot, fig.width=10, fig.height=6, fig.cap="汽車數據可視化"}
library(ggplot2)
# 基本圖形
p <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point(size = 3, alpha = 0.7) +
geom_smooth(method = "lm", se = FALSE) +
labs(
title = "重量與油耗關係",
subtitle = "按氣缸數着色",
x = "重量(千磅)",
y = "油耗(英里/加侖)",
color = "氣缸數"
) +
theme_minimal()
print(p)
# 多個圖形佈局
library(patchwork)
p1 <- ggplot(mtcars, aes(x = mpg)) +
geom_histogram(bins = 15, fill = "steelblue") +
ggtitle("MPG分佈")
p2 <- ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
geom_boxplot(fill = "lightgreen") +
ggtitle("按氣缸數分組")
(p1 | p2) + plot_annotation(title = "汽車數據分析")
```
3.5 圖形交叉引用
# 在文本中引用圖形
如\@ref(fig:cars-plot)所示,汽車的重量與油耗呈負相關關係。
# 也可以這樣寫:
如圖\@ref(fig:cars-plot)所示...
# 對於表格引用:
如表\@ref(tab:summary-table)所示...
# 注意:需要在代碼塊中設置標籤
# ```{r cars-plot, fig.cap="圖形標題"}
# # 圖形代碼
# ```
# YAML頭部需要添加:
# output:
# bookdown::html_document2:
# toc: true
📑 第四部分:報告格式與定製
4.1 YAML頭部配置
---
title: "專業數據分析報告"
author: "數據分析師"
date: "`r format(Sys.Date(), '%Y年%m月%d日')`"
output:
html_document:
theme: united
highlight: tango
toc: true
toc_float: true
toc_depth: 3
number_sections: true
code_folding: show
fig_width: 8
fig_height: 6
fig_caption: true
df_print: paged
css: styles.css
includes:
in_header: header.html
before_body: before_body.html
after_body: after_body.html
pdf_document:
toc: true
number_sections: true
latex_engine: xelatex
includes:
in_header: preamble.tex
word_document:
toc: true
toc_depth: 3
abstract: |
本報告分析了汽車數據集,探討了油耗與各種因素的關係。
主要內容包括描述性統計分析、可視化展示和迴歸模型構建。
keywords:
- 數據分析
- 汽車油耗
- 統計建模
- R語言
subtitle: "汽車油耗影響因素分析"
lang: zh-CN
---
4.2 自定義CSS樣式
/* styles.css - 自定義CSS樣式 */
/* 整體樣式 */
body {
font-family: 'Microsoft YaHei', 'Segoe UI', sans-serif;
line-height: 1.6;
color: #333;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
/* 標題樣式 */
h1 {
color: #2c3e50;
border-bottom: 3px solid #3498db;
padding-bottom: 10px;
}
h2 {
color: #34495e;
border-left: 5px solid #3498db;
padding-left: 15px;
}
h3 {
color: #7f8c8d;
}
/* 代碼塊樣式 */
pre {
background-color: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 5px;
padding: 15px;
}
code {
background-color: #f1f3f4;
color: #d63384;
padding: 2px 4px;
border-radius: 3px;
}
/* 表格樣式 */
table {
border-collapse: collapse;
width: 100%;
margin: 20px 0;
}
th {
background-color: #3498db;
color: white;
padding: 12px;
text-align: left;
}
td {
padding: 10px;
border-bottom: 1px solid #ddd;
}
tr:hover {
background-color: #f5f5f5;
}
/* 引用樣式 */
blockquote {
border-left: 4px solid #3498db;
background-color: #f8f9fa;
padding: 15px;
margin: 20px 0;
font-style: italic;
}
/* 鏈接樣式 */
a {
color: #3498db;
text-decoration: none;
}
a:hover {
text-decoration: underline;
color: #2980b9;
}
/* 特殊類 */
.note {
background-color: #e7f3ff;
border-left: 4px solid #2196f3;
padding: 15px;
margin: 20px 0;
}
.warning {
background-color: #fff3cd;
border-left: 4px solid #ffc107;
padding: 15px;
margin: 20px 0;
}
4.3 LaTeX模板定製
% preamble.tex - LaTeX前言
\usepackage{ctex} % 中文支持
\usepackage{geometry}
\usepackage{graphicx}
\usepackage{booktabs}
\usepackage{caption}
\usepackage{float}
\usepackage{hyperref}
% 頁面設置
\geometry{a4paper, margin=2.5cm}
% 鏈接設置
\hypersetup{
colorlinks=true,
linkcolor=blue,
filecolor=magenta,
urlcolor=cyan,
}
% 自定義命令
\newcommand{\R}{\textsf{R}}
\newcommand{\code}[1]{\texttt{#1}}
% 圖表標題格式
\captionsetup[figure]{labelfont=bf}
\captionsetup[table]{labelfont=bf}
4.4 參數化報告
---
title: "參數化分析報告"
author: "數據分析團隊"
date: "`r Sys.Date()`"
output: html_document
params:
dataset: "mtcars"
variable: "mpg"
group_by: "cyl"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
library(dplyr)
# 使用參數
data <- get(params$dataset)
```
## 分析報告
正在分析數據集:`r params$dataset`
目標變量:`r params$variable`
分組變量:`r params$group_by`
```{r analysis}
# 動態分析
summary_stats <- data %>%
group_by(across(params$group_by)) %>%
summarize(
count = n(),
mean = mean(.data[[params$variable]]),
sd = sd(.data[[params$variable]]),
min = min(.data[[params$variable]]),
max = max(.data[[params$variable]])
)
kable(summary_stats, caption = "描述性統計")
```
```{r visualization, fig.width=10, fig.height=6}
# 動態可視化
ggplot(data, aes(x = .data[[params$group_by]],
y = .data[[params$variable]])) +
geom_boxplot(fill = "lightblue") +
labs(
title = paste(params$variable, "by", params$group_by),
x = params$group_by,
y = params$variable
) +
theme_minimal()
```
🚀 第五部分:高級功能
5.1 交互式元素
# 使用htmlwidgets添加交互式元素
```{r}
# 交互式圖形 - plotly
library(plotly)
p <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point(size = 3) +
theme_minimal()
ggplotly(p) %>%
layout(
title = "交互式汽車數據圖",
hovermode = "closest"
)
```
```{r}
# 交互式表格 - DT
library(DT)
datatable(
mtcars,
options = list(
pageLength = 5,
dom = 'Bfrtip',
buttons = c('copy', 'csv', 'excel')
),
filter = 'top',
caption = '交互式數據表'
)
```
```{r}
# 交互式地圖 - leaflet
library(leaflet)
leaflet() %>%
addTiles() %>%
setView(lng = 116.4074, lat = 39.9042, zoom = 10) %>%
addMarkers(lng = 116.4074, lat = 39.9042,
popup = "北京")
```
5.2 引用與參考文獻
# 引用參考文獻
## 文獻引用
根據Smith的研究[@smith2020ml],機器學習在數據分析中...
近期研究顯示[@jones2021dl],深度學習...
## 參考文獻列表
---
# references.bib 文件內容示例
# @book{smith2020ml,
# title={機器學習導論},
# author={Smith, John},
# year={2020},
# publisher={科學出版社}
# }
#
# @article{jones2021dl,
# title={深度學習在金融中的應用},
# author={Jones, Mary},
# journal={計算機研究},
# volume={48},
# number={3},
# pages={123--135},
# year={2021}
# }
# YAML配置需要添加:
# bibliography: references.bib
# csl: chinese-gb7714-2005-numeric.csl # 中文參考文獻格式
5.3 幻燈片製作
---
title: "數據分析演示文稿"
author: "演講者"
date: "`r Sys.Date()`"
output:
ioslides_presentation:
widescreen: true
smaller: true
transition: faster
---
## 幻燈片1:標題頁
# 數據分析報告
### 汽車油耗影響因素分析
<br>
<br>
`r Sys.Date()`
---
## 幻燈片2:內容大綱
### 報告結構
1. 研究背景
2. 數據描述
3. 分析方法
4. 主要發現
5. 結論建議
---
## 幻燈片3:交互式內容
```{r slide3-plot, echo=FALSE, fig.height=4}
library(plotly)
p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point(aes(color = factor(cyl)), size = 3) +
theme_minimal()
ggplotly(p)
```
汽車重量與油耗的關係如上圖所示。
---
## 幻燈片4:分欄佈局
:::::::::::::: {.columns}
::: {.column width="50%"}
### 左側內容
```{r left-col, echo=FALSE}
library(DT)
datatable(head(mtcars, 5))
```
:::
::: {.column width="50%"}
### 右側內容
- 要點1:油耗與重量負相關
- 要點2:氣缸數影響顯著
- 要點3:自動擋油耗更高
```{r right-col, echo=FALSE, fig.height=3}
boxplot(mpg ~ cyl, data = mtcars, col = "lightblue")
```
:::
::::::::::::::
📋 第六部分:實戰案例
案例1:完整數據分析報告
---
title: "汽車油耗影響因素分析報告"
author: "數據分析團隊"
date: "`r format(Sys.Date(), '%Y年%m月%d日')`"
output:
html_document:
theme: flatly
toc: true
toc_float: true
number_sections: true
code_folding: hide
fig_width: 10
fig_height: 6
abstract: |
本報告使用mtcars數據集,分析影響汽車油耗的主要因素。
通過描述性統計、可視化分析和迴歸建模,探討了氣缸數、
重量、馬力等變量對油耗的影響。
keywords:
- 汽車油耗
- 數據分析
- 迴歸模型
- R語言
---
```{r setup, include=FALSE}
# 初始化設置
knitr::opts_chunk$set(
echo = FALSE,
warning = FALSE,
message = FALSE,
fig.align = "center"
)
# 加載包
library(tidyverse)
library(knitr)
library(kableExtra)
library(ggplot2)
library(plotly)
library(DT)
```
# 執行摘要
本次分析的主要發現:
1. **油耗與汽車重量顯著負相關**(相關係數 = -0.87)
2. **氣缸數對油耗有顯著影響**(4缸車平均油耗最高)
3. **自動擋車輛油耗普遍低於手動擋**
4. 最佳的預測模型是多元線性迴歸模型(R² = 0.85)
```{r summary-stats, echo=FALSE}
# 計算關鍵統計指標
key_stats <- data.frame(
指標 = c("平均油耗", "油耗標準差", "最低油耗", "最高油耗", "樣本數量"),
數值 = c(
round(mean(mtcars$mpg), 2),
round(sd(mtcars$mpg), 2),
min(mtcars$mpg),
max(mtcars$mpg),
nrow(mtcars)
)
)
kable(key_stats, align = c('l', 'c')) %>%
kable_styling(bootstrap_options = c("striped", "hover"))
```
# 1. 數據概覽
## 1.1 數據來源
本次分析使用R內置的`mtcars`數據集,包含1974年《Motor Trend》雜誌測試的32款汽車的11個變量。
## 1.2 變量説明
```{r variable-description, echo=FALSE}
var_desc <- data.frame(
變量名 = names(mtcars),
描述 = c(
"油耗(英里/加侖)",
"氣缸數",
"排量",
"馬力",
"後軸比",
"重量(千磅)",
"1/4英里加速時間",
"發動機類型(V型/直列)",
"變速箱類型(0=自動,1=手動)",
"前進檔數",
"化油器數量"
),
類型 = c(rep("數值型", 11))
)
kable(var_desc, caption = "變量説明") %>%
kable_styling(bootstrap_options = "striped")
```
## 1.3 數據預覽
```{r data-preview, echo=FALSE}
DT::datatable(
mtcars,
caption = "數據集預覽(可交互)",
options = list(
pageLength = 10,
dom = 'Bfrtip',
buttons = c('copy', 'csv')
),
filter = 'top'
)
```
# 2. 描述性分析
## 2.1 油耗分佈
```{r mpg-distribution, echo=FALSE, fig.cap="油耗分佈直方圖"}
ggplot(mtcars, aes(x = mpg)) +
geom_histogram(bins = 15, fill = "steelblue", alpha = 0.7) +
geom_density(aes(y = after_stat(count)), color = "red", size = 1) +
geom_vline(xintercept = mean(mtcars$mpg),
linetype = "dashed",
color = "darkgreen",
size = 1) +
annotate("text",
x = mean(mtcars$mpg) + 3,
y = 5,
label = paste("均值:", round(mean(mtcars$mpg), 2)),
color = "darkgreen") +
labs(title = "油耗分佈", x = "油耗(mpg)", y = "頻數") +
theme_minimal()
```
## 2.2 分組比較
```{r group-comparison, echo=FALSE, fig.cap="按氣缸數分組的油耗箱線圖"}
p1 <- ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(cyl))) +
geom_boxplot(alpha = 0.7) +
labs(title = "按氣缸數分組", x = "氣缸數", y = "油耗", fill = "氣缸數") +
scale_fill_brewer(palette = "Set2") +
theme_minimal()
p2 <- ggplot(mtcars, aes(x = factor(am), y = mpg, fill = factor(am))) +
geom_boxplot(alpha = 0.7) +
labs(title = "按變速箱類型分組",
x = "變速箱(0=自動,1=手動)",
y = "油耗",
fill = "變速箱") +
scale_fill_brewer(palette = "Set3") +
theme_minimal()
library(patchwork)
p1 + p2 + plot_layout(guides = "collect")
```
## 2.3 相關性分析
```{r correlation, echo=FALSE, fig.cap="變量間相關矩陣熱力圖"}
library(corrplot)
cor_matrix <- cor(mtcars[, c("mpg", "cyl", "disp", "hp", "wt")])
corrplot(cor_matrix,
method = "color",
type = "upper",
order = "hclust",
addCoef.col = "black",
tl.col = "black",
tl.srt = 45,
diag = FALSE,
title = "主要變量相關矩陣",
mar = c(0, 0, 2, 0))
```
# 3. 迴歸分析
## 3.1 簡單線性迴歸
```{r simple-regression, echo=FALSE, fig.cap="油耗與重量關係的迴歸分析"}
lm_simple <- lm(mpg ~ wt, data = mtcars)
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point(size = 3, alpha = 0.7, color = "steelblue") +
geom_smooth(method = "lm", color = "red", se = TRUE) +
labs(
title = paste("油耗與重量關係 (R² =",
round(summary(lm_simple)$r.squared, 3), ")"),
x = "重量(千磅)",
y = "油耗(mpg)"
) +
theme_minimal() +
annotate("text",
x = 4.5,
y = 30,
label = paste("公式: mpg =",
round(coef(lm_simple)[1], 2),
round(coef(lm_simple)[2], 2), "* wt"),
color = "red",
size = 5)
```
## 3.2 多元迴歸模型
```{r multiple-regression, echo=FALSE}
lm_multi <- lm(mpg ~ wt + hp + factor(cyl) + factor(am), data = mtcars)
# 創建迴歸結果表格
coef_table <- data.frame(
變量 = names(coef(lm_multi)),
係數估計值 = round(coef(lm_multi), 3),
標準誤 = round(summary(lm_multi)$coefficients[, 2], 3),
t值 = round(summary(lm_multi)$coefficients[, 3], 2),
p值 = format.pval(summary(lm_multi)$coefficients[, 4], digits = 3)
)
kable(coef_table, caption = "多元迴歸模型係數") %>%
kable_styling(bootstrap_options = "striped") %>%
row_spec(which(coef_table$p值 < 0.05), bold = TRUE, color = "red")
```
```{r model-summary, echo=FALSE}
# 模型摘要
model_summary <- data.frame(
指標 = c("R²", "調整R²", "F統計量", "F檢驗p值", "殘差標準誤"),
值 = c(
round(summary(lm_multi)$r.squared, 3),
round(summary(lm_multi)$adj.r.squared, 3),
round(summary(lm_multi)$fstatistic[1], 1),
format.pval(pf(summary(lm_multi)$fstatistic[1],
summary(lm_multi)$fstatistic[2],
summary(lm_multi)$fstatistic[3],
lower.tail = FALSE), digits = 3),
round(summary(lm_multi)$sigma, 3)
)
)
kable(model_summary, align = c('l', 'c')) %>%
kable_styling(bootstrap_options = "striped")
```
# 4. 結論與建議
## 4.1 主要發現
1. **重量是影響油耗的最主要因素**,重量每增加1000磅,油耗平均減少5.34 mpg
2. **氣缸數對油耗有顯著影響**,6缸和8缸車油耗明顯高於4缸車
3. **手動擋車輛油耗略高於自動擋**,但差異不顯著
4. **馬力對油耗的影響較小**,在控制其他變量後不顯著
## 4.2 建議
基於以上分析,我們建議:
1. **輕量化設計**:汽車製造商應注重輕量化設計以降低油耗
2. **發動機優化**:在保證動力的前提下,優化發動機效率
3. **消費者選擇**:消費者可選擇重量較輕、氣缸數較少的車型以降低油耗
# 附錄
## 附錄A:完整R代碼
```{r full-code, eval=FALSE, echo=TRUE}
# 完整分析代碼
library(tidyverse)
library(ggplot2)
# 數據加載
data(mtcars)
# 描述性分析
summary(mtcars$mpg)
hist(mtcars$mpg)
# 迴歸分析
model <- lm(mpg ~ wt + hp + factor(cyl), data = mtcars)
summary(model)
# 可視化
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_smooth(method = "lm")
```
## 附錄B:參考文獻
1. Henderson, H. V., & Velleman, P. F. (1981). Building multiple regression models interactively. *Biometrics*, 37(2), 391-411.
2. R Core Team (2023). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria.
---
*報告生成時間:`r Sys.time()`*
*報告版本:1.0*
*分析工具:R `r R.version.string`*
案例2:參數化週報模板
---
title: "銷售週報 - 第`r params$week`周"
author: "銷售分析部"
date: "`r Sys.Date()`"
output: html_document
params:
week: 1
region: "全國"
start_date: !r as.Date("2023-01-01")
end_date: !r as.Date("2023-12-31")
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)
library(tidyverse)
library(ggplot2)
library(plotly)
library(lubridate)
```
# `r params$region`銷售週報(第`r params$week`周)
**報告期間:** `r format(params$start_date, "%Y年%m月%d日")` - `r format(params$end_date, "%Y年%m月%d日")`
**生成時間:** `r Sys.time()`
## 執行摘要
```{r summary-data, echo=FALSE}
# 生成模擬銷售數據
set.seed(params$week * 123)
n_days <- as.numeric(params$end_date - params$start_date) + 1
sales_data <- data.frame(
date = seq(params$start_date, params$end_date, by = "day"),
sales = 10000 + cumsum(rnorm(n_days, mean = 100, sd = 500)),
orders = round(runif(n_days, 50, 200)),
customers = round(runif(n_days, 30, 150))
)
# 計算周度彙總
weekly_summary <- sales_data %>%
mutate(week = isoweek(date)) %>%
filter(week == params$week) %>%
summarize(
total_sales = sum(sales),
avg_daily_sales = mean(sales),
total_orders = sum(orders),
new_customers = sum(customers),
avg_order_value = sum(sales) / sum(orders)
)
# 顯示關鍵指標
metrics <- data.frame(
指標 = c("總銷售額", "日均銷售額", "總訂單數", "新客户數", "平均訂單價值"),
數值 = c(
paste("¥", format(weekly_summary$total_sales, big.mark = ",")),
paste("¥", format(round(weekly_summary$avg_daily_sales), big.mark = ",")),
weekly_summary$total_orders,
weekly_summary$new_customers,
paste("¥", format(round(weekly_summary$avg_order_value), big.mark = ","))
)
)
kable(metrics, align = c('l', 'c')) %>%
kable_styling(bootstrap_options = "striped")
```
## 詳細分析
### 銷售額趨勢
```{r sales-trend, echo=FALSE, fig.width=12, fig.height=6}
weekly_sales <- sales_data %>%
mutate(week = isoweek(date)) %>%
group_by(week) %>%
summarize(
week_start = min(date),
total_sales = sum(sales)
)
ggplot(weekly_sales, aes(x = week_start, y = total_sales)) +
geom_line(color = "steelblue", size = 1.5) +
geom_point(color = "darkblue", size = 3) +
geom_point(data = weekly_sales %>% filter(week == params$week),
color = "red", size = 5) +
labs(
title = paste("周銷售額趨勢(當前周:第", params$week, "周)"),
x = "周開始日期",
y = "周銷售額(¥)"
) +
theme_minimal() +
scale_y_continuous(labels = scales::comma)
```
### 產品類別分析
```{r product-analysis, echo=FALSE, fig.width=10, fig.height=6}
# 模擬產品類別數據
product_data <- data.frame(
category = c("電子產品", "家居用品", "服裝配飾", "食品飲料", "圖書音像"),
sales = c(35000, 28000, 22000, 18000, 12000) * runif(5, 0.8, 1.2),
growth = c(15, 12, 8, -5, 3) + rnorm(5, 0, 2)
)
ggplot(product_data, aes(x = reorder(category, sales), y = sales, fill = growth)) +
geom_bar(stat = "identity") +
geom_text(aes(label = paste("¥", format(round(sales), big.mark = ","))),
hjust = -0.2, size = 3.5) +
geom_text(aes(label = paste0(ifelse(growth > 0, "+", ""),
round(growth, 1), "%")),
hjust = 1.2, size = 3.5, color = "white") +
scale_fill_gradient2(low = "red", mid = "white", high = "green", midpoint = 0) +
coord_flip()