String R中字符串的自动首字母缩略词

String R中字符串的自动首字母缩略词,string,r,parsing,String,R,Parsing,情节中的长串并不总是有吸引力的。用R写首字母缩略词的最短方法是什么?例如,“Hello world”到“HW”,最好有唯一的首字母缩略词 有函数缩写,但它只是从短语中删除一些字母,而不是每个单词的第一个字母。一个简单的方法是将strsplit、substr和make.unique组合使用 下面是一个可以编写的示例函数: makeInitials <- function(charVec) { make.unique(vapply(strsplit(toupper(charVec), "

情节中的长串并不总是有吸引力的。用R写首字母缩略词的最短方法是什么?例如,“Hello world”到“HW”,最好有唯一的首字母缩略词


有函数
缩写
,但它只是从短语中删除一些字母,而不是每个单词的第一个字母。

一个简单的方法是将
strsplit
substr
make.unique
组合使用

下面是一个可以编写的示例函数:

makeInitials <- function(charVec) {
  make.unique(vapply(strsplit(toupper(charVec), " "), 
                     function(x) paste(substr(x, 1, 1), collapse = ""), 
                     vector("character", 1L)))
}

使用regex可以执行以下操作。正则表达式模式
(?你建议如何处理重复的缩写?@AnandaMahto也许可以添加第二个字母,如“Hello World”→ 如果“HW”被占用,那么“HeW”?@Anton添加第二个字母确实是个坏主意,因为它可能会导致大量递归循环。@ChinmayPatil,
缩写
应该可以处理它,但是如果你查看函数的代码,它比我们的任何一个答案都要复杂:-)
X <- c("Hello World", "Home Work", "holidays with children", "Hello Europe")
makeInitials(X)
# [1] "HW"   "HW.1" "HWC"  "HE"  
abbreviate(X, minlength=1)
#            Hello World              Home Work holidays with children           Hello Europe 
#                  "HlW"                  "HmW"                  "hwc"                   "HE" 
X <- c("Hello World", "Home Work", "holidays with children")
sapply(regmatches(X, gregexpr(pattern = "((?<=\\s).|^.)", text = X, perl = T)), paste, collapse = ".")
## [1] "H.W"   "H.W"   "h.w.c"

# If you want to make unique
make.unique(sapply(regmatches(X, gregexpr(pattern = "((?<=\\s).|^.)", text = X, perl = T)), paste, collapse = "."))
## [1] "H.W"   "H.W.1" "h.w.c"