Efficiently perform row-wise distribution test

前端 未结 4 622
陌清茗
陌清茗 2021-01-05 02:43

I have a matrix in which each row is a sample from a distribution. I want to do a rolling comparison of the distributions using ks.test and save the test statis

4条回答
  •  無奈伤痛
    2021-01-05 03:19

    Here's a dplyr solution that gets the same result as your loop. I have my doubts if this is actually faster than the loop, but perhaps it can serve as a first step towards a solution.

    require(dplyr)
    mt %>% 
      as.data.frame %>%
      mutate_each(funs(lag)) %>%
      cbind(mt) %>%
      slice(-1) %>%
      rowwise %>%
      do({
        x = unlist(.)
        n <- length(x)
        data.frame(ks = ks.test(head(x, n/2), tail(x, n/2))$statistic)
      }) %>%
      unlist %>%
      c(NA, .) %>%
      matrix
    

提交回复
热议问题