【发布时间】: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)
但是时间太长了。有什么提高性能的建议吗?
【问题讨论】:
-
可以请
dput几行all_postcodes$pcode吗? How to create a minimal, reproducible example -
抱歉 - 刚刚这样做了!感谢您的建议!
-
你可能想改用
(g)sub("[ ]{2,}",' ', x),这样更通用
标签: r performance gsub sapply