我想从一组全名(后缀和全名都是字符向量)中删除一组后缀。使用两个for()
循环和gsub()
这很容易,但似乎应该有一个更有效的方法(无论是在代码行还是时钟循环中)。使用rapply从字符名称向量中的字符向量
我的第一个想法是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
错误是我认为,因为你没有在你的'inner.fun'中引用“replace”。不知道如何用'rapply'做到这一点,但我相信有比循环更好的方法... – joran