【问题标题】:R - Create list of numbers [closed]R - 创建数字列表[关闭]
【发布时间】:2016-04-28 03:45:50
【问题描述】:

我有一个定义了一些颜色的命名向量。

my_colors = c("C_T" = "salmon", "C_G" = "gold", "C_A" = "mediumseagreen", "T_G" = "lightseagreen", "T_C" = "royalblue1", "T_A" = "orchid1")

我想创建一个大小为 N 的列表,其中每个条目都以数字命名并包含向量 my_colors。列表的结构需要适合特定的格式,因为我将它提供给一些非常严格的函数。下面是一些手动生成所需结果并展示必要结构的代码:

my_list = list("1" = my_colors, "2" = my_colors, "3" = my_colors, "4" = my_colors, "5" = my_colors, "6" = my_colors)
str(my_list)

我尝试编写一个循环来填充一个空列表

test_list = list()
for (i in 1:6) {
  test_list[i] = my_colors
}

但这会返回抱怨长度的错误消息

我也试过

test_list = list()
for (i in 1:6) {
  test_list[[i]] = my_colors
}

test_list = list()
for (i in 1:6) {
  x = character(i) 
  test_list[x] = my_colors
}

但是这些方法都没有给我一个与 my_list 具有相同结构的 test_list。如何重新创建用于以递归方式填充 my_list 的手动列表生成?

【问题讨论】:

  • rep(list(my_colors), N)?
  • 试试my_list <- 'names<-'(rep(list(my_colors), n), 1:n)
  • 在循环中使用test_list[[i]] = my_colors 的方法似乎工作正常..?
  • replicate(6,my_colors, simplify=FALSE)
  • 你的第二个 test_list 对我来说很好,并且产生与你的硬编码相同的结构。

标签: r list recursion data-structures


【解决方案1】:

如果你从这个开始(你的努力不应该引发任何错误)

test_list = list()
for (i in 1:6) {
  test_list[[i]] = my_colors
}

...唯一缺少的是正确的名称。轻松修复:

names(test_list) <- 1:6

哦。现在我看到@PierreLafortune 已经建议了。如果在添加 .Names 属性之前,您已经在这两个对象上运行了 all.equal,您会看到这个(可能有帮助)结果:

> all.equal(my_list, test_list)
[1] "names for target but not for current"

您也可以通过键入来查看底层结构

 dput(my_list)
 dput(test_list)

....并注意到“外部”属性存在差异。

【讨论】:

    猜你喜欢
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    • 2018-02-26
    • 1970-01-01
    • 2018-11-09
    • 2019-04-07
    相关资源
    最近更新 更多