如何将多级嵌套列表展平到指定深度?

How can I flatten a multilevel nested list to a specified depth?

我正在尝试将具有 3 个级别的列表展平为具有 2 个级别的列表....换句话说,我有一个这样的嵌套列表:

ls <- list(
  a = list(
    a1 = list(
       a11 = list(data),
    a2 = list(
       a21 = list(data2)),
  b = list(
    b1 = list(
       b11 = list(data3),
    b2 = list(
       b21 = list(data4)))
  

我想把它展平成这样:

flat_ls <- list(
  a_a1 = list(
     a11 = list(data),
  a_a2 = list(
     a21 = list(data2)),
  b_b1 = list(
     b11 = list(data3),
  b_b2 = list(
     b21 = list(data4)))
  

我知道函数 flatten()lapply(rapply(y, enquote, how="unlist"), eval) 可以将多级列表变成平面列表。但是,我想保留列表的最后一层,而不展平它。我怎样才能做到这一点?

purrr::flatten() 实际上完全符合您的要求。根据 (purrr) 文档,flatten() 和朋友们“只删除了一层层次结构。”

library(purrr)

# placeholder values for `data` etc
data <- as.symbol("data")
data2 <- as.symbol("data2")
data3 <- as.symbol("data3")
data4 <- as.symbol("data4")

# added a few missing parens; raised error in original
ls <- list(
  a = list(
    a1 = list(
      a11 = list(data)
    ),
    a2 = list(
      a21 = list(data2)
    )
  ),
  b = list(
    b1 = list(
      b11 = list(data3)
    ),
    b2 = list(
      b21 = list(data4)
    )
  )
)

# (added step in response to comment): 
# combine top two levels of names
ls_renamed <- imap(ls, ~ set_names(.x, paste(.y, names(.x), sep = "_")))

# flatten top level
flat_ls <- flatten(ls_renamed)

dput(flat_ls)
# list(
#   a_a1 = list(
#     a11 = list(data)
#   ), 
#   a_a2 = list(
#     a21 = list(data2)
#   ), 
#   b_b1 = list(
#     b11 = list(data3)
#   ), 
#   b_b2 = list(
#     b21 = list(data4)
#   )
# )