我有一個類似于以下虛擬物件的嵌套串列:
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")
第一級被命名,而第二級沒有。我想根據第一級名稱和 pos 索引將名稱分配給串列的第二級,因此該串列的結構如下所示:
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
有誰知道如何解決這個問題?我將不勝感激。
uj5u.com熱心網友回復:
替代選項:
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))
uj5u.com熱心網友回復:
使用 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
uj5u.com熱心網友回復:
一個for回圈怎么樣?
for (i in seq_along(nested_list)) {
names(nested_list[[i]]) <- paste(names(nested_list)[i],
seq_along(nested_list[[i]]),
sep = "_")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/364189.html
上一篇:如何重新排序串列中的多個df
