【问题标题】:How can I use accumulate like reduce2 function in purrr?如何在 purrr 中使用像 reduce2 一样的累积函数?
【发布时间】:2018-05-11 15:43:39
【问题描述】:

我想将accumulate 函数与两个输入向量和reduce2 函数一起使用。 accumulate 的文档暗示可以给出两个输入向量并且accumulate 可以与reduce2 一起使用。但是,我遇到了麻烦。

这是一个示例,灵感来自 reduce2 的文档。

这是来自reduce2的示例

> paste2 <- function(x, y, sep = ".") paste(x, y, sep = sep)
> letters[1:4] %>% reduce2(.y=c("-", ".", "-"), paste2)
[1] "a-b.c-d"

这里有几次尝试使用accumulate,类似于reduce2。没有一个正确地遍历letters[1:4]c("-",".","-")

> letters[1:4] %>% accumulate(.y=c("-", ".", "-"),paste2)
Error in .f(x, y, ...) : unused argument (.y = c("-", ".", "-"))

> letters[1:4] %>% accumulate(c("-", ".", "-"),paste2)
[[1]]
[1] "a"

[[2]]
NULL

> letters[1:4] %>% accumulate(sep=c("-", ".", "-"),paste2)
[1] "a"       "a-b"     "a-b-c"   "a-b-c-d"

如何使用accumulate 查看reduce2 示例给出的中间结果?

【问题讨论】:

    标签: r tidyverse purrr


    【解决方案1】:

    这可能是一个疏忽,文档根本不是最新的/有点误导?我也无法让accumulate 接受一个三参数函数,我很惊讶你的最后一个示例中没有错误,尽管我猜它必须是paste 抛出它。 .f 的文本与 accumulatereduce 的文本完全相同,这一事实让我认为 accumulate 中不存在此功能。此外,查看源代码似乎表明(除非我误读)reducereduce2 有自己的实现,但 accumulate 依赖于 base::Reduce。可能值得一个 GitHub 问题。

    这是产生您想要的输出的最佳方法。它基本上涉及多次调用reduce2,将输入列表的正确子集和次要输入向量传递给paste2,感觉不是很整洁。这可能不是一个特别整洁的问题。请注意使用{} 覆盖默认%&gt;% 将管道LHS 作为第一个参数的行为,以及reduce2 内部.x.y 上的不同索引(我们希望保留.y.x短一个元素)。

    paste2 <- function(x, y, sep = ".") paste(x, y, sep = sep)
    
    library(purrr)
    letters[1:4] %>%
      {map_chr(
        .x = 2:length(.),
        .f = function(index) reduce2(
          .x = .[1:index],
          .y = c("-", ".", "-")[1:(index - 1)],
          .f = paste2
        )
      )}
    #> [1] "a-b"     "a-b.c"   "a-b.c-d"
    

    reprex package (v0.2.0) 于 2018 年 5 月 11 日创建。

    【讨论】:

      【解决方案2】:

      几个月后after 这个帖子accumulate2 被介绍了,给出了 OP 之后的结果:

      library(purrr)
      
      paste2 <- function(x, y, sep = ".") paste(x, y, sep = sep)
      accumulate2(letters[1:4], c("-", ".", "-"), paste2)
      
      #> [[1]]
      #> [1] "a"
      #> 
      #> [[2]]
      #> [1] "a-b"
      #> 
      #> [[3]]
      #> [1] "a-b.c"
      #> 
      #> [[4]]
      #> [1] "a-b.c-d"
      

      【讨论】:

        【解决方案3】:

        通过这个技巧,您可以在accumulate 中使用无限参数,而您甚至不需要accumulate2

        library(tidyverse)
        
        x <- letters[1:4]
        y <- c('-', '.', '-')
        
        accumulate(seq_along(x[-1]), .init = x[1], ~paste(.x, x[.y+1], sep = y[.y]))
        #> [1] "a"       "a-b"     "a-b.c"   "a-b.c-d"
        
        # OR
        
        accumulate(seq_along(y), .init = x[1], ~paste(.x, x[.y+1], sep = y[.y]))
        #> [1] "a"       "a-b"     "a-b.c"   "a-b.c-d"
        

        reprex package (v2.0.1) 于 2022-02-21 创建

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-03-16
          • 2018-05-13
          • 1970-01-01
          • 2018-11-07
          • 2015-12-29
          • 2021-01-21
          • 2011-10-24
          相关资源
          最近更新 更多