【问题标题】:How to get and set elements in nested list如何获取和设置嵌套列表中的元素
【发布时间】:2014-01-28 23:07:41
【问题描述】:

假设我有以下结构:

R 代码

listAll = list()
list3 = list(id=14,attr1 = '',attr2='n4',attr3=list(text1='tx1',text2=''))
list4 = list(id=15,attr1 = '',attr2='n1',attr3=list(text1='tx1',text2=''))
listAll = append(listAll,list(values=list3))
listAll = append(listAll,list(values=list4))
str(listAll)

#result

List of 2
$ values:List of 4
..$ id   : num 14
..$ attr1: chr ""
..$ attr2: chr "n4"
..$ attr3:List of 2
.. ..$ text1: chr "tx1"
.. ..$ text2: chr ""
$ values:List of 4
..$ id   : num 15
..$ attr1: chr ""
..$ attr2: chr "n1"
..$ attr3:List of 2
.. ..$ text1: chr "tx1"
.. ..$ text2: chr ""

我如何设置/获取例如属于 id 14 的 attr2?

我认为这不难......我所要做的就是(获取):

  1. 获取搜索到的 id 的索引
  2. 获取该索引对应的列表
  3. 从第二步的列表中获取 $attr1 的值

不幸的是,我不知道如何完成第一点。

假设我有 id = 14 和相应的索引 1..下一步将是(两个和三个一起):

listAll[[1]]$attr2 #results "n4"

所以问题是如何获得与 id = 14 匹配的索引(在本例中 = 1)。 有人可以帮忙吗?

【问题讨论】:

    标签: r list nested


    【解决方案1】:

    你可以使用sapply实现你想要的

    ##  sapply(listAll, "[[", "id")
    ## werte werte 
    ##    14    15 
    

    然后你可以申请which这样获取索引

    which(sapply(listAll, "[[", "id") == 14)
    ## werte   
    ##     1 
    
    which(sapply(listAll, "[[", "id") == 15)
    ## werte 
    ##     2 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-15
      • 2023-02-04
      • 2022-10-05
      • 2020-12-17
      • 1970-01-01
      • 2015-03-01
      • 1970-01-01
      • 2014-01-23
      相关资源
      最近更新 更多