【问题标题】:Creating a sublist for elements within a list of lists after creation of list object在创建列表对象后为列表列表中的元素创建子列表
【发布时间】:2019-08-12 06:54:22
【问题描述】:

示例列表:

sublist <- list(foo = "foo", bar = "bar", baz = "baz")

sample_list <- list(a = sublist,
                    b = sublist,
                    c = sublist)

在这里,我想在上述每个列表中为 a bc 中的元素创建一个子列表。即我想嵌套foobarbaz,再往下嵌套一个列表,在我以上述方式创建列表之后

期望的输出:

sample_list <- list(a = list(a_down = sublist),
                    b = list(b_down = sublist),
                    c = list(c_down = sublist))

【问题讨论】:

  • 类似lapply(1:3, function(i) setNames(list(sublist), letters[i]))?

标签: r list recursion


【解决方案1】:

我们可以使用imap

library(purrr)
out2 <- imap(sample_list, ~ set_names(list(.x), paste0(.y, "_down"))) 

或使用lst

imap(sample_list, ~ lst(!! paste0(.y, "_down") := .x))

-检查 OP 的输出

identical(out, out2)
#[1] TRUE

【讨论】:

    猜你喜欢
    • 2017-06-26
    • 1970-01-01
    • 2011-09-07
    • 2019-10-26
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多