情节中的长弦并不总是吸引人的。在R中做首字母缩写的最短方法是什么?例如,"Hello“改为"HW",最好有独特的首字母缩写。
有函数abbreviate,但它只是从短语中删除一些字母,而不是取每个单词的首字母。
发布于 2013-12-01 06:17:01
一个简单的方法是使用strsplit、substr和make.unique的组合。
下面是一个可以编写的示例函数:
makeInitials <- function(charVec) {
make.unique(vapply(strsplit(toupper(charVec), " "),
function(x) paste(substr(x, 1, 1), collapse = ""),
vector("character", 1L)))
}试一试:
X <- c("Hello World", "Home Work", "holidays with children", "Hello Europe")
makeInitials(X)
# [1] "HW" "HW.1" "HWC" "HE" 尽管如此,我确实认为,如果使用abbreviate的一些论点,那么它就足够了:
abbreviate(X, minlength=1)
# Hello World Home Work holidays with children Hello Europe
# "HlW" "HmW" "hwc" "HE" 发布于 2013-12-01 06:37:23
使用regex,您可以执行以下操作。regex模式((?<=\\s).|^.)查找任何字母,后面跟着空格或字符串的第一个字母。然后,我们只使用paste生成向量,使用collapse参数获得第一个基于字母的缩略词。正如Ananda所建议的,如果您想要使结果通过make.unique进行唯一的传递。
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"https://stackoverflow.com/questions/20309267
复制相似问题