R-根据`purrr'中的条件从列表中提取元素

时间:2019-06-15 00:32:49

标签: r data-manipulation purrr

我有以下HTML输入列表。列表具有嵌套结构-

  1. 级别1包含输入的名称(例如input1)。
  2. 第2级包含有关每个输入的一些信息-nameattribschildren
  3. 第3级分支出children,它是长度为2的列表-第一个元素包含有关输入标签的信息,第二个元素包含有关输入类型的信息。由于需要输入标签,因此需要为每个输入提取此列表的第一个元素。

列表:

library(purrr)

inputs = list(
  input1 = list(
    name = 'div', 
    attribs = list(class = 'form-group'), 
    children = list(list(name = 'label', 
                         attribs = list(`for` = 'email'), 
                         children = list('Email')), 
                    list(
                      list(name = 'input', 
                           attribs = list(id = 'email', type = 'text'), 
                           children = list()))
                    )))

str(inputs)
List of 1
 $ input1:List of 3
  ..$ name    : chr "div"
  ..$ attribs :List of 1
  .. ..$ class: chr "form-group"
  ..$ children:List of 2
  .. ..$ :List of 3
  .. .. ..$ name    : chr "label"
  .. .. ..$ attribs :List of 1
  .. .. .. ..$ for: chr "email"
  .. .. ..$ children:List of 1
  .. .. .. ..$ : chr "Email"
  .. ..$ :List of 1
  .. .. ..$ :List of 3
  .. .. .. ..$ name    : chr "input"
  .. .. .. ..$ attribs :List of 2
  .. .. .. .. ..$ id  : chr "email"
  .. .. .. .. ..$ type: chr "text"
  .. .. .. ..$ children: list()

我可以使用keep()has_element来做到这一点:

label = input %>% 
  map_depth(2, ~keep(., ~has_element(., 'label'))) %>%
  map('children') %>%
  flatten %>% 
  map('children') %>%
  flatten

输出:

str(label)
List of 1
 $ input1: chr "Email"

当我浏览purrr帮助页面时,keep似乎是我所追求的功能,但是我仍然必须两次使用mapflatten才能获得标签,看起来很笨拙。所以我想知道是否有更直接的方法来实现相同的输出?我对解决方案的兴趣不大,因为我对使用此类嵌套列表背后的想法很感兴趣。

2 个答案:

答案 0 :(得分:1)

如果每个输入都具有相同的结构,则不需要EncryptionAlgorithm.AES192,它用于删除不满足某些条件的列表元素。相反,您可以像这样通过keep进行映射。当然,此方法将删除与每个输入相关的所有其他数据。如果最终目标是“重组”,即采用平面结构获取每个输入的所有信息,则可能需要做一些不同的事情。

pluck

reprex package(v0.3.0)于2019-06-14创建

答案 1 :(得分:0)

尝试:

map(inputs, "children") %>% map_depth(2, "children")

输出:

$input1
$input1[[1]]
$input1[[1]][[1]]
[1] "Email"


$input1[[2]]
NULL