刚开始尝试使用 Officedown 在 Rmarkdown 中格式化文本。我的最终目标是通过循环遍历数据框来有条件地格式化对象列表。我无法ftext
输出任何东西,最后只有在我将函数拉到 for 循环之外才让它工作。
ftext()
关于为什么在 for 循环之外会输出,但在循环内部不会输出,我是否遗漏了什么?这是我的代码:
---
title: "ftext Test with looping"
date: "`r Sys.Date()`"
output:
officedown::rdocx_document: default
---
{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(officedown)
library(officer)
data <- data.frame(value = c("This should be frmtted","This shouldn't","Neither should this","But this should be"),
frmt = c(TRUE,FALSE,FALSE,TRUE),
stringsAsFactors = FALSE)
{r output dei, echo = FALSE, results='asis'}
ft <- fp_text(font.size = 12, bold = TRUE, color = "#C32900", font.family = "Cambria")
output <- c("Line 1","Line 2","Line 3","Line 4")
cat('### Outputting longhand')
i <- 1
cat("\n * ")
if (data$frmt[i]){ftext(data$value[i],ft)} else {cat(data$value[i])}
i <- 2
cat("\n * ")
if (data$frmt[i]){ftext(data$value[i],ft)} else {cat(data$value[i])}
i <- 3
cat("\n * ")
if (data$frmt[i]){ftext(data$value[i],ft)} else {cat(data$value[i])}
i <- 4
cat("\n * ")
if (data$frmt[i]){ftext(data$value[i],ft)} else {cat(data$value[i])}
{r output loop, echo = FALSE, results='asis'}
ft <- fp_text(font.size = 12, bold = TRUE, color = "#C32900", font.family = "Cambria")
output <- c("Line 1","Line 2","Line 3","Line 4")
cat('### Outputting using loop')
for (i in 1:length(output)){
cat("\n * ")
if (data$frmt[i]){ftext(data$value[i],ft)} else {cat(data$value[i])}
}
这就是它产生的结果:
显然,我不想每次都把所有的东西都写出来,所以希望能够ftext()
在 for 循环中使用。关于为什么它可能不起作用的任何建议?