r - 需要向量化字符串上的函数
问题描述
我有一个 300K 行数据框,其中有一列如下:
db$performance[1:10]
[1] "1C1CCCCCCCCCCCCCCCCCCCCCC" "CCCCCCCCCCCCC"
"4321CCCCCCCCCCCCCCCCCCCCC" "321CCCCCCCCCCCCCCCCCCCCCC"
[5] "CCCCCCCCCCCCCC" "4321CCCCCCCCCCCCC0" "211CCCCCCCCCCCCCCCCCCCCCC" "BCCCCCCCCC" [9] "BCCCCCCCCC" "8"
我想搜索该列的每一行并计算最后(从右到左)18 个字符元素中出现的“4”的数量。我的循环解决方案显然很糟糕,因为它非常慢(6 分钟或更长时间)。见下文。我如何矢量化解决方案(使用 apply 和/或 dplyr?)
谢谢你!
substrRight <- function(x, n){
substr(x, nchar(x)-n, nchar(x))
}
db$NewVar = NA
for (N in 1:nrow(db)){
db$NewVar[N] = str_count( substrRight(db$performance[N],18), "4")
}
解决方案
str_count
并且substr
已经矢量化。所以,直接在整列上应用函数
library(stringr)
str_count(substrRight(db$performance, 18), "4")
#[1] 0 0 0 0 0 1 0 0 0 0
它应该足够快。在更大的数据集上检查时间
基准
db1 <- db[rep(seq_len(nrow(db)), 1e5),, drop = FALSE]
system.time({
out <- numeric(nrow(db1))
for (i in seq_len(nrow(db1))){
out[i]= str_count( substrRight(db1$performance[i],18), "4")
}
})
# user system elapsed
# 14.699 0.104 14.755
system.time({
sapply(db1$performance, function(x) str_count( substrRight(x,18), "4") )
})
# user system elapsed
# 14.267 0.075 14.299
system.time({
str_count(substrRight(db1$performance, 18), "4")
})
# user system elapsed
# 0.437 0.016 0.452
数据
db <- structure(list(performance = c("1C1CCCCCCCCCCCCCCCCCCCCCC", "CCCCCCCCCCCCC",
"4321CCCCCCCCCCCCCCCCCCCCC", "321CCCCCCCCCCCCCCCCCCCCCC", "CCCCCCCCCCCCCC",
"4321CCCCCCCCCCCCC0", "211CCCCCCCCCCCCCCCCCCCCCC", "BCCCCCCCCC",
"BCCCCCCCCC", "8")), class = "data.frame", row.names = c(NA,
-10L))
推荐阅读
- java - 在 Vaadin Flow 网络应用程序中设置我的“UI”子类的内容
- javascript - Microsoft Edge 中是否有与 window.clipboardData 等效的内容?
- python - 辅助修复 While 循环
- excel - 使用 Excel 验证条目
- android - 错误:com.google.android.gms.internal.measurement.zzdz
- memory - Kubernetes Pod OOMKilled 解决方案
- javascript - 如何编写更好的 React 列表容器组件?
- java - 查找数组Java的模式
- r - 从堆栈溢出问题中的代码块中删除空格
- django - 没有频道层或任何其他免费托管的频道