首页 > 解决方案 > 在 R 中,是否可以在文本段落中调用函数并删除中断?

问题描述

我正在尝试为非 R 用户编写一个函数,用于在 R markdown 中编写报告。该函数为宏字符调用 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')

读书:

一些东西和一些带有长音的东西。

标签: rfunctionunicodeline-breaks

解决方案


您将获得多行,因为您将列表传递给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')

推荐阅读