我将如何编写 purrr::keep 的递归版本? [英] How would I write a recursive version of purrr::keep?

查看:33
本文介绍了我将如何编写 purrr::keep 的递归版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个嵌套列表,其中包含一堆不同级别的数据框.我想仅提取数据框的扁平列表.我如何使用 purrr 函数编写它?我应该查看 reduce 吗?

Say I have a nested list with a bunch of data frames at different levels. I want to extract out flattened list of just the data frames. How might I write this using purrr functions? Should I be looking at reduce?

例如,给定数据:

s <- list(x = 1:10,
          data = data.frame(report = LETTERS[1:5],
                            value = rnorm(5, 20, 5)),
          report = list(A = data.frame(x = 1:3, y = c(2, 4, 6)),
                        B = data.frame(x = 1:3, y = c(3, 6, 9)),
                        z = 4:10,
                        other = data.frame(w = 3:5,
                                       color = c("red", "green", "blue"))))

我希望函数返回:

list(data = data.frame(report = LETTERS[1:5],
                       value = rnorm(5, 20, 5)),
     `report$A` = data.frame(x = 1:3, y = c(2, 4, 6)),
     `report$B` = data.frame(x = 1:3, y = c(3, 6, 9)),
     `report$other` = data.frame(w = 3:5,
                                 color = c("red", "green", "blue")))

我写了一个递归函数:

recursive_keep <- function(.x, .f) {
  loop <- function(.y) {
    if(is.list(.y)) {
      c(keep(.y, .f), flatten(map(discard(.y, .f), loop)))
    } else if(.f(.y)) {
      .y
    } else {
      NULL
    }
  }
  loop(.x)
}

它可以被称为:

recursive_keep(s, is.data.frame)

它似乎适用于这个示例,但它没有保留名称信息.我希望保留足够的信息,以便我可以从原始对象中提取数据.也许这是一个更容易回答的问题?

It seems to work on this example, but it doesn't keep the name information. I'm looking to keep enough information that I could pluck the data from the original object. Maybe that is an easier question to answer?

推荐答案

这个单行体的递归函数保留名称并且不使用包:

This recursive function with one-line body retains names and uses no packages:

rec <- function(x, FUN = is.data.frame)
  if (FUN(x)) list(x) else if (is.list(x)) do.call("c", lapply(x, rec, FUN))

str(rec(s))  # test

给予(输​​出后继续):

giving (continued after output):

List of 4
 $ data        :'data.frame':   5 obs. of  2 variables:
  ..$ report: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
  ..$ value : num [1:5] 29.1 19.9 21.2 13 25.2
 $ report.A    :'data.frame':   3 obs. of  2 variables:
  ..$ x: int [1:3] 1 2 3
  ..$ y: num [1:3] 2 4 6
 $ report.B    :'data.frame':   3 obs. of  2 variables:
  ..$ x: int [1:3] 1 2 3
  ..$ y: num [1:3] 3 6 9
 $ report.other:'data.frame':   3 obs. of  2 variables:
  ..$ w    : int [1:3] 3 4 5
  ..$ color: Factor w/ 3 levels "blue","green",..: 3 2 1

关于从原始对象sreport中获取A:

Regarding getting, say, A from within report from the original object s:

s[["report"]][["A"]]

ix <- c("report", "A")
s[[ix]]

这篇关于我将如何编写 purrr::keep 的递归版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆