问题描述
我正在尝试为非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')
阅读:
有些东西和一个大颗粒一起存在。
解决方法
由于要向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 ','nd something with a macron')