我在資料集中有 2 列:id和text
同一 ID 存在多個文本。我的目標是通過回圈 ID 號生成多個 PDF 檔案(每個 ID 一個)。但是,我希望每個 pdf 都包含該 ID 號的所有文本(以表格格式使用knitr::kable())
這是我擁有的 .Rmd 檔案的可重現示例:
---
title: "Loop over grouped IDs"
output:
pdf_document:
latex_engine: xelatex
params:
id: i
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, include= FALSE)
library(tidyverse)
df <- tibble(
text = c(
"text one for id#1",
"text two for id#1",
"text one for id#12",
"text one for id#13",
"text two for id#13",
"text three for id#13",
"text one for id#15",
"text two for id#15"
),
id = c(1, 1, 12, 13, 13, 13, 15, 15)
)
df_id_filtered <- df %>% filter(id == params$id)
```
## Hello ID\#`r df_id$id[i]`!
These are the collections of texts that belong to you
```{r, echo=FALSE, results='asis'}
texts <- df_id_filtered$text
table <- knitr::kable(texts, col.names = "text")
```
`r table`
我為回圈代碼創建了一個 .R 腳本,如下所示:
library(rmarkdown)
library(knitr)
# loop through the id rows in the filtered data frame and generate a pdf report for each ID with all the texts in the "text" column for that ID
for (i in seq_along(df_id_filtered)) {
rmarkdown::render(input = "idText.Rmd",
params = list(id = i),
output_format = "pdf_document",
output_file = paste0("File", "_", "ID#", i, ".pdf"))
}
回圈是如何鏈接到params: id確切的?如果我回圈整個df而不是回圈,df_id_filtered那么相同 ID 號的文本將在單獨的檔案中。
seq_along()這里是正確的選擇嗎?什么應該在params = list()?
我的代碼有效,但它不適用于整個唯一 ID(僅適用于其中的 2 個)。
任何幫助是極大的贊賞!謝謝!
uj5u.com熱心網友回復:
seq_along(df_id_filtered)如果您想遍歷所有ID's,我認為這里不是正確的選擇。df_id_filtered是資料框,seq_along它會遍歷列。由于您的資料中有 2 列,因此它僅針對 2 個 ID 運行。
你可以試試——
library(rmarkdown)
library(knitr)
for (i in unique(df$id)) {
rmarkdown::render(input = "idText.Rmd",
params = list(id = i),
output_format = "pdf_document",
output_file = paste0("File", "_", "ID#", i, ".pdf"))
}
所以在這里我們遍歷unique id資料中的each并為它撰寫一個pdf。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/388500.html
上一篇:從R中的文本中提取串列項
