首页 > 解决方案 > 是否可以重命名列表中的多个列表名称?

问题描述

我想在列表中重命名我的列表名称。

例如:

library(randNames) #using this package for the random names for the example
my_info <- rand_names(10)
my_second_info <- rand_names(10)

list1 <- list(A = c(my_info$name.first), B = c(rnorm(1:10)), C = c(rnorm(1:10)), D = c(rnorm(1:10)))
list2 <- list(A = c(my_second_info$name.first), B = c(rnorm(1:10)), C = c(rnorm(1:10)), D = c(rnorm(1:10)))

both_lists <- list(list1,list2)

现在,当我调用 both_lists 时,我将 [[1]] 作为第一个列表的名称,将 [[2]] 作为第二个列表的名称(如此处所示)。

我想将 list1 和 list2 的名称(以及可能添加到其中的所有其他名称)更改为名字随机名称。因此,列表 1 将命名为 both_lists[[1]]$A[1],而列表 2 将命名为 both_lists[[2]]$A[1]。

这可能吗?或者列表名称是否会丢失,例如在制作列表列表时它只是变成一个特定的数字?

标签: rlistapply

解决方案


您可以使用从所有列表中的子列表中sapply提取第一个值并将其分配为名称。A

names(both_lists) <- sapply(both_lists, function(x) x$A[1])

推荐阅读