使用gsub和sapply的R性能问题

Nic*_*ick 0 performance r gsub sapply

我有一个由+10万条记录组成的数据框(all_postcodes).[编辑]这里只是几条记录:

pcode  area  east    north   area2     area3      area4      area5
AB101AA 10  394251  806376  S92000003 S08000006  S12000033  S13002483
AB101AB 10  394232  806470  S92000003 S08000006  S12000033  S13002483
AB101AF 10  394181  806429  S92000003 S08000006  S12000033  S13002483
AB101AG 10  394251  806376  S92000003 S08000006  S12000033  S13002483
Run Code Online (Sandbox Code Playgroud)

我想使用以下函数创建一个包含其中一列的规范化版本的新列:

pcode_normalize <- function (x) {
x <- gsub("  ", " ", x)
if (length(which(strsplit(x, "")[[1]]==" ")) == 0) {
x <- paste(substr(x, 1, 4), substr(x, 5, 7))
}
x
}
Run Code Online (Sandbox Code Playgroud)

我试着按如下方式执行它:

all_postcodes$npcode <- sapply(all_postcodes$pcode, pcode_normalize)
Run Code Online (Sandbox Code Playgroud)

但这需要太长时间.有什么建议如何提高性能?

Jos*_*ich 6

您使用的所有功能pcode_normalize都已经过矢量化.没有必要循环使用sapply.它看起来像你正在strsplit寻找单一空间.grepl会更快.

使用fixed=TRUE您的来电gsub,并grepl会更快,因为你没有实际使用正则表达式.

pcode_normalize <- function (x) {
  x <- gsub("  ", " ", x, fixed=TRUE)
  sp <- grepl(" ", x, fixed=TRUE)
  x[!sp] <- paste(substr(x[!sp], 1, 4), substr(x[!sp], 5, 7))
  x
}
all_postcodes$npcode <- pcode_normalize(all_postcodes$pcode)
Run Code Online (Sandbox Code Playgroud)

我实际上无法对此进行测试,因为您没有提供任何示例数据,但它应该让您走上正确的道路.