【问题标题】:R performance issues using gsub and sapply使用 gsub 和 sapply 的 R 性能问题
【发布时间】:2014-03-24 13:18:53
【问题描述】:

我有一个包含 +1000 万条记录 (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

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

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
}

我尝试如下执行:

all_postcodes$npcode <- sapply(all_postcodes$pcode, pcode_normalize)

但是时间太长了。有什么提高性能的建议吗?

【问题讨论】:

标签: r performance gsub sapply


【解决方案1】:

您在pcode_normalize 中使用的所有函数都已矢量化。无需使用sapply 循环。看起来您也在使用 strsplit 来查找单个空格。 grepl 会更快。

在调用gsubgrepl 时使用fixed=TRUE 会更快,因为您实际上并没有使用正则表达式。

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)

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

【讨论】:

  • 你是对的 - 它可以工作并且速度快如闪电!最大的改进是删除 sapply (以前我不得不停止 R,因为它需要一个多小时)但是你的函数版本也快得多。现在没有 sapply 并且使用您的代码只需不到一秒钟的时间。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多