Quickest way to find closest elements in an array in R

前端 未结 3 1469
青春惊慌失措
青春惊慌失措 2021-01-29 00:21

I would like find the fastes way in R to indentify indexes of elements in Ytimes array which are closest to given Xtimes values.

So far I have been using a simple for-lo

3条回答
  •  礼貌的吻别
    2021-01-29 01:22

    R is vectorized, so skip the for loop. This saves time in scripting and computation. Simply replace the for loop with an apply function. Since we're returning a 1D vector, we use sapply.

    YmatchIndex <- sapply(Xtimes, function(x){which.min(abs(Ytimes - x))})


    Proof that apply is faster:

    library(microbenchmark)
    library(ggplot2)
    
    # set up data
    Xtimes <- c(1,5,8,10,15,19,23,34,45,51,55,57,78,120)
    Ytimes <- seq(0,120,length.out = 1000)
    
    # time it
    mbm <- microbenchmark(
      for_loop = for (i in 1:length(Xtimes)) {
        YmatchIndex[i] = which.min(abs(Ytimes - Xtimes[i]))
      },
      apply    = sapply(Xtimes, function(x){which.min(abs(Ytimes - x))}),
      times = 100
    )
    
    # plot
    autoplot(mbm)
    

    See ?apply for more.

提交回复
热议问题