簡體   English   中英

將 r 代碼插入到 Rmarkdown 文件中未硬編碼的文本中

[英]Inserting r code into text that is not hardcoded in Rmarkdown file

我正在使用 Rmarkdown 創建一個文檔。 該文檔將有許多不同的版本,並且不同版本的所有文本都已寫入 Excel 電子表格,然后將其讀入 Rmarkdown 文件。 在文本中,有時報告之間會有所不同,方括號中的關鍵字需要替換為 r 代碼。 我無法讓 rcode 在文本中進行評估並在 Rmarkdown output 中正確打印出來。

# Text like that in the Excel spreadsheet
report_text <- ("There are [NumberFruit] fruits in the fruitbowl. [HighestPercent]% of the fruit are [HighestPercentType].")

#Extract variables within the square brackets
variables <- str_extract_all(report_text, "\\[[A-Z,a-z]+\\]")

# Define all varaibles - the variables are the same in each report. The data in the actual report differs and is defined from a dataframe. 
for (i in unlist(variables)){
  if(grepl("NumberFruit", i)){
    NumberFruit <- 10
    
  } else if(grepl("HighestPercent", i)){
    HighestPercent <- 56
    
  } else if(grepl("HighestPercentType", i)){
    HighestPercentType <- "apples"
    
  } else if (length(unlist(variables)) > 3){
    stop("Additional VARIABLE:",i, "has not been assigned")
  }
}

一旦定義了變量,我通常會使用如下所示的內容,但由於文本沒有硬編碼到 Rmarkdown 文件中,這種方法是不可能的。

final_text <- paste0("There are ",NumberFruit, "  fruits in the fruitbowl. ",HighestPercent, "% are ",HighestPercentType, ".")

所以我嘗試按照上面的粘貼選項格式化文本,但這不會產生所需的 output。

report_text2 <- gsub('\\[', '",',(gsub('\\]', ', "', report_text)))

#Also tried
report_text2 <- paste0(gsub('\\[', '",',(gsub('\\]', ', "', report_text))))

然后我在 Rmarkdown 文本中使用r final text來創建報告中的文本。 上述代碼的兩個版本具有相同的結果,如下所示。

當前Rmarkdown output:水果碗里有“,NumberFruit”水果。 ",HighestPercent, "水果的百分比是 ",HighestPercentType, "。"

所需的 Rmarkdown output:水果碗里有 10 個水果。 56%的水果是蘋果。

我已經用谷歌搜索了有關其他嘗試的線索,但找不到任何東西,並且有點卡在從這里到 go 的位置。 任何有關如何使這項工作的建議將不勝感激。 我通常不處理文本字符串,並且覺得我在這里遺漏了一些基本的東西。

如果我們需要插入在RMD文件中創建的變量,一個選項是使用glue

library(glue)
library(stringr)
final_text <- glue::glue(str_replace_all(str_replace_all(report_text,
         "\\[", "{"),  "\\]", "}"))

RMD文件中的完整代碼

---
title: "test"
author: "akrun"
date: "16/03/2021"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown


```{r test1}
report_text <- "There are [NumberFruit] fruits in the fruitbowl. [HighestPercent]% of the fruit are [HighestPercentType]."
NumberFruit <- 10
HighestPercent <- 56
HighestPercentType <- "apples"
```

```{r test2}

library(stringr)
final_text <- glue::glue(str_replace_all(str_replace_all(report_text, "\\[", "{"), "\\]", "}"))

```

`r final_text`

-輸出

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM