Speeding up function that uses which within a sapply call in R

拟墨画扇 提交于 2019-11-30 09:34:24

The reason this is so slow is because you're calling your function length(e) times. It doesn't make a large difference for small vectors, but the overhead from R function calls really starts to add up with larger vectors.

Normally, you would need to move this to compiled code, but luckily you can use findInterval:

set.seed(21)
e <- rnorm(1e4)
g <- rnorm(1e4)
O <- findInterval(e,sort(g))/length(g)

# Now for some timings:
f <- function(p,v) mean(v<=p)
system.time(o <- sapply(e, f, g))
#   user  system elapsed 
#   0.95    0.03    0.98
system.time(O <- findInterval(e,sort(g))/length(g))
#   user  system elapsed 
#      0       0       0 
identical(o,O)  # may be FALSE
all.equal(o,O)  # should be TRUE

# How fast is this on large vectors?
set.seed(21)
e <- rnorm(1e7)
g <- rnorm(1e7)
system.time(O <- findInterval(e,sort(g))/length(g))
#   user  system elapsed 
#  22.08    0.08   22.31
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!