简体   繁体   English

如何从复杂列表中提取嵌套元素?

[英]How to extract nested elements from a complex list?

I am working with a list with this structure.我正在使用具有这种结构的列表。 I want to extract the "contactId" of every contact into a new list.我想将每个联系人的“contactId”提取到一个新列表中。

surveys<-list(


  list(
    list(contactId = 2234, age= 24, unsuscribed = FALSE), 
    list(contactId = 6234, age= 23, unsuscribed = FALSE),
    list(contactId = 8234, age= 21, unsuscribed = FALSE)
    ),
  
  list(
    list(contactId = 1124, age= 28, unsuscribed = FALSE), 
    list(contactId = 1874, age= 15, unsuscribed = FALSE),
    list(contactId = 1674, age= 35, unsuscribed = FALSE),
    list(contactId = 1324, age= 45, unsuscribed = FALSE),
    list(contactId = 1234, age= 65, unsuscribed = FALSE)
  ),
  
  
  list(
    list(contactId = 1334, age= 18, unsuscribed = FALSE), 
    list(contactId = 1224, age= 45, unsuscribed = FALSE)
    

  )
) 

I am using the following line of code and it returns me all the data of the first contact of each sublist.我正在使用以下代码行,它返回每个子列表的第一个联系人的所有数据。

sapply(surveys, "[[",1)

Any help will be appreciated.任何帮助将不胜感激。 Thanks in advance.提前致谢。

The sapply returns a matrix with elements as list . sapply返回一个元素为listmatrix We could extract further using the rownames我们可以使用行名进一步提取

unlist(sapply(surveys, "[[",1)['contactId',])

If we want to extract all the elements, do a nested lapply/sapply and extract by the list names in the inner list如果我们想提取所有元素,请执行嵌套 lapply/sapply 并通过内部列表中的列表名称提取

lapply(surveys, function(x) sapply(x, function(y) y[['contactId']]))

-output -输出

[[1]]
[1] 2234 6234 8234

[[2]]
[1] 1124 1874 1674 1324 1234

[[3]]
[1] 1334 1224

Or another option is to use a recursive function ( rrapply ) to extract from the inner most vector或者另一种选择是使用递归函数( rrapply )从最里面的向量中提取

library(purrr)
library(rrapply)
library(magrittr)
rrapply(surveys,  classes = c("ANY", "vector"),
  f = function(x, .xname)  x[.xname == 'contactId']) %>%
  map(unlist, use.name = FALSE)
[[1]]
[1] 2234 6234 8234

[[2]]
[1] 1124 1874 1674 1324 1234

[[3]]
[1] 1334 1224

You could also write a small function to do this:您还可以编写一个小函数来执行此操作:

get_elem <- function(x, elem){
  if(!is.list(x[[1]])) x[[elem]]
  else sapply(x, get_elem, elem)
}

get_elem(surveys, 'contactId')
[[1]]
[1] 2234 6234 8234

[[2]]
[1] 1124 1874 1674 1324 1234

[[3]]
[1] 1334 1224

 get_elem(surveys, 'age')
[[1]]
[1] 24 23 21

[[2]]
[1] 28 15 35 45 65

[[3]]
[1] 18 45

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM