r - 在 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')
读书:
一些东西和一些带有长音的东西。
解决方案
您将获得多行,因为您将列表传递给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')
推荐阅读
- tsql - sql代码比较系列中的前一行
- vba - 在 PST 存储中隐藏搜索文件夹
- r - 将单元格内容分成R中的新行
- c - strcasecmp 算法有缺陷吗?
- scala - 如何基于 Spark/Scala 中所有列的过滤条件创建 DF
- r - 使用 .SD 对 data.table 中的列子集进行累积总和
- java - 复杂的 sql 查询应该发生在后端还是在 android mobile 中安全
- mongodb - Mongo Express 服务器监听 http://0.0.0.0:8081
- javascript - react中的分页类组件
- cassandra - 连接错误: ('无法连接到任何服务器', {'127.0.0.1': error(111, "尝试连接到 [('127.0.0.1