【问题标题】:Name second level of nested list in R在R中命名第二级嵌套列表
【发布时间】:2022-01-02 01:59:13
【问题描述】:

我有一个类似于以下虚拟对象的嵌套列表:

list1 <- list(1:3, 4:7, 8:10)
list2 <- list(2:5, 4:9, 19:23, 15:18)
list3 <- list(1:5)

nested_list <- list(list1, list2, list3)
names(nested_list) <- c("first", "second", "third")

第一层被命名,而第二层没有。我想根据第一级名称和位置索引为列表的第二级分配名称,因此该列表的结构如下所示:

List of 3
 $ first :List of 3
  ..$ first_1: int [1:3] 1 2 3
  ..$ first_2: int [1:4] 4 5 6 7
  ..$ first_3: int [1:3] 8 9 10
 $ second:List of 4
  ..$ second_1: int [1:4] 2 3 4 5
  ..$ second_2: int [1:6] 4 5 6 7 8 9
  ..$ second_3: int [1:5] 19 20 21 22 23
  ..$ second_4: int [1:4] 15 16 17 18
 $ third :List of 1
  ..$ third_1: int [1:5] 1 2 3 4 5

有谁知道如何解决这个问题?我将不胜感激。

【问题讨论】:

    标签: r list nested


    【解决方案1】:

    for 循环怎么样?

    for (i in seq_along(nested_list)) {
       names(nested_list[[i]]) <- paste(names(nested_list)[i], 
                                        seq_along(nested_list[[i]]), 
                                        sep = "_")
    }
    

    【讨论】:

    • 谢谢你哦,聪明人。
    • 谢谢 cmets 实际上在 SO 上已被弃用,但如果它解决了您的问题,欢迎您点击复选标记接受答案
    【解决方案2】:

    备选方案:

    setNames(lapply(seq_along(nested_list), function(x) { setNames(nested_list[[x]],paste(names(nested_list)[x], 1:length(nested_list[[x]]), sep="_")) }), names(nested_list))
    

    【讨论】:

    • 这很好,但您可以添加一些换行符吗?
    【解决方案3】:

    使用imap

    library(purrr)
    library(stringr)
    nested_list <- imap(nested_list, ~ setNames(.x, str_c(.y, "_", seq_along(.x))))
    

    -输出

    > str(nested_list)
    List of 3
     $ first :List of 3
      ..$ first_1: int [1:3] 1 2 3
      ..$ first_2: int [1:4] 4 5 6 7
      ..$ first_3: int [1:3] 8 9 10
     $ second:List of 4
      ..$ second_1: int [1:4] 2 3 4 5
      ..$ second_2: int [1:6] 4 5 6 7 8 9
      ..$ second_3: int [1:5] 19 20 21 22 23
      ..$ second_4: int [1:4] 15 16 17 18
     $ third :List of 1
      ..$ third_1: int [1:5] 1 2 3 4 5
    

    【讨论】:

      猜你喜欢
      • 2020-12-06
      • 2022-11-17
      • 2021-01-12
      • 2016-06-04
      • 1970-01-01
      • 2020-10-29
      • 2020-10-06
      • 2023-03-29
      • 1970-01-01
      相关资源
      最近更新 更多