Cor*_*one 5 string formatting r r-markdown
在使用rmarkdown它时,通常需要以编程方式生成文本片段,特别是列出正在使用的项目.例如;
The species of iris examined were `r cat(as.character(unique(iris$Species)), sep = ", ")`.
Run Code Online (Sandbox Code Playgroud)
哪个会产生
检查的虹膜种类是setosa,versicolor,virginica.
要正确阅读它应该是
检查的虹膜种类是setosa,versicolor和virginica.
有一个简单的方法吗?
这是pander包中有用的工具之一
为了漂亮的内联打印,p将一个向量的元素合并在一个字符串中.从适当的选项值读取默认参数(有关详细信息,请参阅参数说明).此功能允许你把其产生可变直列,通过缠绕在提供的字符串向量元素的表达式的结果涡卷,和分离由主要和结束分隔符(元件九月和系动词).在双长度矢量的情况下,copula中指定的值将用作分隔符.您还可以通过更改limit参数中指定的整数值来控制提供的向量的长度(默认为Inf).
例:
devtools::install_github('Rapporter/pander')
## also available on cran:
# install.packages('pander')
library(pander)
p(levels(iris$Species), wrap = '')
# "setosa, versicolor and virginica"
p(levels(iris$Species), wrap = '', copula = ', and ')
# "setosa, versicolor, and virginica"
Run Code Online (Sandbox Code Playgroud)
这里有这样一个函数
wordlist<-function(w, oxford=F) {
if(length(w)==1) return(w);
if(length(w)==2) return(paste(w[1],"and",w[2]));
paste0( paste(w[-length(w)], collapse=", "),
ifelse(oxford,",","")," and ", w[length(w)] )
}
wordlist(unique(iris$Species))
# [1] "setosa, versicolor and virginica"
Run Code Online (Sandbox Code Playgroud)
(根据 OP 的示例,oxford 设置为 false)
| 归档时间: |
|
| 查看次数: |
210 次 |
| 最近记录: |