【问题标题】:Is it possible to rename multiple list names in a list?是否可以重命名列表中的多个列表名称?
【发布时间】:2021-08-04 17:52:38
【问题描述】:

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

例如:

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]] 作为第二个列表的名称 (as depicted here)。

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

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

【问题讨论】:

    标签: r list apply


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以使用names() 来做到这一点

      names(both_lists) &lt;- c(both_lists[[1]]$A[1],both_lists[[2]]$A[1])

      【讨论】:

        【解决方案3】:

        当您在sapply 中使用unlist 时,您可以通过在第一行中获得的值来使用setNames

        both_lists <- setNames(both_lists, sapply(both_lists, unlist)[1,])
        
        names(both_lists)
        # [1] "Vilma" "Naomi"
        

        数据:我将你的代码用于set.seed(42)

        【讨论】:

          猜你喜欢
          • 2021-09-26
          • 2015-10-23
          • 2014-01-26
          • 2018-08-22
          • 2011-10-02
          • 2022-08-09
          • 1970-01-01
          • 2012-08-30
          • 1970-01-01
          相关资源
          最近更新 更多