我想从一组全名中删除一组后缀(后缀和全名都是字符向量)。for()
使用两个循环和非常容易gsub()
,但似乎应该有一种更有效的方法(在代码行和时钟周期中)。
我的第一个想法是rapply()
,但我无法让它工作。也许for()
循环是最好的方法,但在这一点上,我有兴趣更好地理解rapply()
这是for()
循环版本。
names.full <- c("tom inc", "dick co", "harry incorp", "larry inc incorp", "curly", "moe")
suffix <- c("inc", "incorp", "incorporated", "co", "company")
suffix <- paste(" ", suffix, "$", sep = "")
# with loops
names.abbr <- names.full
for (k in seq(2)) {
for (i in seq(length(names.abbr))) {
for (j in seq(length(suffix))) {
names.abbr[i] <- gsub(suffix[j], "", names.abbr[i])
}
}
}
还有我失败的rapply()
版本。
# with rapply
inner.fun <- function(y, x) {
rapply(as.list(x), function(x) gsub(y, "", x), how = "replace")
}
names.abbr.fail <- unlist(rapply(as.list(suffix), inner.fun, x = names.full, how = replace))
这给出了以下错误:
> names.abbr.fail <- unlist(rapply(as.list(suffix), inner.fun, x = names.full, how = replace))
Error in match.arg(how) : 'arg' must be NULL or a character vector