Speed up the loop operation in R

前端 未结 10 2115
说谎
说谎 2020-11-22 00:04

I have a big performance problem in R. I wrote a function that iterates over a data.frame object. It simply adds a new column to a data.frame and a

10条回答
  •  情歌与酒
    2020-11-22 00:18

    Take a look at the accumulate() function from {purrr} :

    dayloop_accumulate <- function(temp) {
      temp %>%
        as_tibble() %>%
         mutate(cond = c(FALSE, (V6 == lag(V6) & V3 == lag(V3))[-1])) %>%
        mutate(V10 = V9 %>% 
                 purrr::accumulate2(.y = cond[-1], .f = function(.i_1, .i, .y) {
                   if(.y) {
                     .i_1 + .i
                   } else {
                     .i
                   }
                 }) %>% unlist()) %>%
        select(-cond)
    }
    

提交回复
热议问题