在 R 中,是否可以在文本段落中调用函数并删除中断?

In R, is it possible to call a function in a text paragraph and remove the breaks?

我正在尝试为非 R 用户编写一个函数,用于在 R markdown 中编写报告。 该函数为 macron 字符调用 unicode。

代码:

library(stringr)
library(Unicode)
library(htmltools)
library(cat)

mac <- function(x){
         if (x == "a") {
  result <- "\u101"
  } else if (x == "A") {
  result <- "\u100"
  } else if (x == "e") {
  result <- "\u113"
  } else if (x == "E") {
  result <- "\u112"
  } else if (x == "i") {
  result <- "\u12b"
  } else if (x == "I") {
  result <- "\u12a"
  } else if (x == "o") {
  result <- "\u14d"
  } else if (x == "O") {
  result <- "\u14c"
  } else if (x == "u") {
  result <- "\u16b"
  } else if (x == "U") {
  result <- "\u16a"
  } else (print("Entry not recognised")) 
  
  result = paste0(result, sep = "")

  return(result)
  # return(p(paste0(result, sep = "")))
  
}

我试过:

  # gsub("[\r\n]", "", result)
  # str_replace_all(x, "[\r\n]" , "")

没有任何成功 - 我意识到这是因为要删除的函数输出周围没有空格。

举个例子,我想要这个:

p('Something',mac("a"),'nd something with a macron')

阅读:

东西和带长音符的东西。

您得到多行,因为您将列表传递给 p()

如果将文本换行在 paste0 中,输出应该全部在一行上。

输入:

p(paste0('Something ',mac("a"),'nd something with a macron'))

输出:

<p>Something ānd something with a macron</p>

显示为:

长音符号的东西

这可以包装在一个函数中:

p <- function(...) htmltools::p(paste0(...))

如果您预计用户会尝试将列表传递给 p(),那么您可以添加一些内容来处理这些异常。

完整代码及使用示例:

library(stringr)
library(Unicode)
library(htmltools)
library(cat)

mac <- function(x){
    if (x == "a") {
        result <- "\u101"
    } else if (x == "A") {
        result <- "\u100"
    } else if (x == "e") {
        result <- "\u113"
    } else if (x == "E") {
        result <- "\u112"
    } else if (x == "i") {
        result <- "\u12b"
    } else if (x == "I") {
        result <- "\u12a"
    } else if (x == "o") {
        result <- "\u14d"
    } else if (x == "O") {
        result <- "\u14c"
    } else if (x == "u") {
        result <- "\u16b"
    } else if (x == "U") {
        result <- "\u16a"
    } else (print("Entry not recognised")) 
    
    result = paste0(result, sep = "")
    
    return(result)
    # return(p(paste0(result, sep = "")))
    
}

# wrap input in paste0() to create a string then pass to p()
p <- function(...) htmltools::p(paste0(...))

# example use
p('Something ',mac("a"),'nd something with a macron')