r - 如何通过 R 中的手动矢量化来提高自定义函数的性能
问题描述
我有两个数据框:df1 提供给定符号的坐标,df2 提供开始和结束坐标。我需要获取 df2 中每个开始和结束坐标之间的符号序列。
例如:
set.seed(1)
df1 <- data.frame(POS = 1:10000000,
REF = sample(c("A", "T", "G", "C"), 10000000, replace = T))
df2 <- data.frame(start = sample(1:5000000, 10, replace = T),
end = sample(5000001:10000000, 10, replace = T))
我尝试使用 for 循环:
system.time( {
df2$seq <- NA
for(i in 1:nrow(coords)){
df2$seq[i] <- paste(ref$REF [ c( which(ref$POS == coords$start[i]) : which(ref$POS == coords$end[i]) ) ], collapse = "")
}
})
并使用手动矢量化:
mongoose <- function(from, to){
string <- paste(
ref$REF [ c( which(ref$POS == from) : which(ref$POS == to) ) ],
collapse = "")
return(string)
}
mongoose_vec <- Vectorize(mongoose, vectorize.args = c("from", "to"))
system.time({
sequences <- mongoose_vec(from = df2$start, to = df2$end)
})
但是,这两种方法都以相似的速度执行,并且速度不够快,因为我应用它们的数据集非常大。有没有人对如何提高性能有任何建议?
解决方案
Vectorize 不会显着加快您的任务,因为它只会减少开销,但大部分计算都在循环本身内。
您可以采取的一种方法是存储ref
为长字符串并使用该substr
函数。
ref2 <- paste0(ref$REF, collapse="")
system.time({
sequences2 <- sapply(1:nrow(coords), function(i) {
substr(ref2, coords$start[i], coords$end[i])
})
})
user system elapsed
0.135 0.010 0.145
您的原始代码:
system.time({
sequences <- mongoose_vec(from = coords$start, to = coords$end)
})
user system elapsed
7.914 0.534 8.461
结果是相同的:
identical(sequences, sequences2)
TRUE
PS:我假设df1
是ref
并且df2
是coords
。
推荐阅读
- asp.net - 需要登录才能查看页面
- node.js - Node Joi:joi键的值必须与joi数组中的一个对象键匹配
- javascript - 嗨,你们有没有人设法在 typeOrm 中使用 vanilla javaScript 实现双向关系?
- php - Laravel:如何将数据从一个连接复制到另一个?
- javascript - useEffect 重写整个商店
- css - 带有双连字符(双破折号)的类的 CSS
- tomcat - Tomcat 负载均衡器
- foreach - MyBatis 如何在 select 语句中使用 foreach?
- docker - docker 中 jupyter 的性能比原生模式慢 15 倍。我从哪里开始发现问题?
- java - 无法从 Collection<> 转换为 List<>