【问题标题】:List of a lists in R using an indexR中使用索引的列表列表
【发布时间】:2020-06-09 23:27:08
【问题描述】:

我想在 R 中添加一个列表作为另一个列表的元素。这似乎可行,但我不知道语法。我尝试了多种不同的方法,并提出了以下四个示例来说明问题。

我的目标是接近示例 3,我可以在其中编写类似于:a$b[5]$c = 7 的语句。

示例 #1

> q = list()
> q[1] = list(1,2)
Warning message:
In q[1] = list(1, 2) :
  number of items to replace is not a multiple of replacement length

示例 #2:

> a = list()
> a$b = list()
> a$b[1] = list()
> a$b[2] = list(1)
> a$b[3] = list(1,2)
Warning message:
In a$b[3] = list(1, 2) :
  number of items to replace is not a multiple of replacement length

示例 #3:

> a$b[5]$c = 7
Warning message:
In a$b[5]$c = 7 :
  number of items to replace is not a multiple of replacement length

示例 #4:

第 1 部分

> w = list("1"=list(1,1), "2"=list(2,2))
> w
$`1`
$`1`[[1]]
[1] 1

$`1`[[2]]
[1] 1


$`2`
$`2`[[1]]
[1] 2

$`2`[[2]]
[1] 2

第 #2 部分

> w[1] = 5
> w
$`1`
[1] 5

$`2`
$`2`[[1]]
[1] 2

$`2`[[2]]
[1] 2

【问题讨论】:

  • 使用双括号:q[[1]] = list(1, 2)

标签: r list syntax


【解决方案1】:

正如@Rohit 所说,使用双括号有效。这通过允许以下操作解决了这个问题:

> a = list()
> a$b = list()
> a$b[[10]] = list(1,2)
> a$b[[5]] = list(1,2,3)
> a$b[[4]] = 0
> a$b[[3]] = list()
> a$b[[3]]$c = 0
> a$b[[20]] = 5
> a$b[[30]] = list()
> a$b[[40]] = list(1,2)
> a$b[[50]] = list()
> a$b[[50]]$c = list()
> a$b[[50]]$b = 5
> a$b[[50]]$k = list()
> a$b[[50]]$k[1] = list()

【讨论】:

    【解决方案2】:

    这通常在 lattice 包的幕后完成,使用的函数是modifyList。这是帮助页面示例。但是,我认为此函数无法完成对子列表中编号元素的分配。它只为命名列表定义。

     ?modifyList
     foo <- list(a = 1, b = list(c = "a", d = FALSE))
     bar <- modifyList(foo, list(e = 2, b = list(d = TRUE)))
     str(foo)
    #------
    List of 2
     $ a: num 1
     $ b:List of 2
      ..$ c: chr "a"
      ..$ d: logi FALSE
    #-------
     str(bar)
    #----
    List of 3
     $ a: num 1
     $ b:List of 2
      ..$ c: chr "a"
      ..$ d: logi TRUE
     $ e: num 2
    #--------
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-13
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      • 2018-01-17
      • 2019-05-25
      • 1970-01-01
      相关资源
      最近更新 更多