我有一个数据框
df_full
,我想循环遍历它以创建四开本的目录。我希望每个主题中的每个标题为 unique(df_full$Topic)
,每个副标题为 unique(df_full$question_id)
,显示的内容为 unique(df_full$response)
。
我的尝试是这样的:
---
title: "PSP ESG and Impact Orientation QAQC"
format:
html:
toc: true
toc-depth: 2
number-sections: true
toc-location: left
css: corp-styles_2023-new-logo.css
self-contained: true
editor: visual
execute:
echo: false
warning: false
editor_options:
chunk_output_type: console
---
# Loop through unique topics
for (topic in unique(df_full$Topic)) {
cat("#", topic, "\n") # Main section for each Topic
# Filter to get questions and responses for the current topic
topic_data <- df_full |>
filter(Topic == topic)
for (i in 1:nrow(topic_data)) {
# Use Question as a subsection
cat("## Question:", topic_data$Question[i], "\n")
# Add the dummy response
cat("### Response:", topic_data$dummy_response[i], "\n")
}
}
但是结果只是显示为这样的文本:
# ESG Governance and Disclosure
## Question: Formal ESG policy or policies on relevant environmental, social, governance topics?
### Response: Yes, policy or strategy in place
## Question: Formal ESG policy or policies on relevant environmental, social, governance topics?
### Response: Yes, policy or strategy in place
## Question: Formal ESG policy or policies on relevant environmental, social, governance topics?
### Response: Yes, policy or strategy in place
如果您的代码生成原始 Markdown 并且您希望保持原样,您还应该相应地设置
output
(或 results
)选项,例如:
```{r}
#| output: asis
cat("# Topic\n")
```
完整的qmd供参考:
---
format:
html:
toc: true
toc-depth: 2
number-sections: true
toc-location: left
self-contained: true
editor: visual
execute:
echo: false
warning: false
editor_options:
chunk_output_type: console
---
```{r}
#| label: setup
library(dplyr)
df_full <- tribble(
~Topic, ~Question, ~dummy_response,
"A", "B", "C"
)
```
Code-block with `output: asis`:
```{r}
#| label: with-output-asis
#| output: asis
# Loop through unique topics
for (topic in unique(df_full$Topic)) {
cat("#", topic, "\n") # Main section for each Topic
# Filter to get questions and responses for the current topic
topic_data <- df_full |>
filter(Topic == topic)
for (i in 1:nrow(topic_data)) {
# Use Question as a subsection
cat("## Question:", topic_data$Question[i], "\n")
# Add the dummy response
cat("### Response:", topic_data$dummy_response[i], "\n")
}
}
```
---
Code-block without `output: asis` :
```{r}
#| label: without-output-asis
cat("#", topic, "\n")
cat("## Question:", topic_data$Question[i], "\n")
cat("### Response:", topic_data$dummy_response[i], "\n")
```
渲染为: