How to check that element of a list of lists matches a condition?

只谈情不闲聊 提交于 2020-08-22 05:49:10

问题


I have a list of lists:

  pairs <- list(
    list(Name="A",Value=11), 
    list(Name="B",Value=17), 
    list(Name="C",Value=23)
  )

How can I check that pairs list contains an element with Name=="A"? And I'd also like to get that element.


回答1:


If you just want to know whether any list component has Name=='A':

any(sapply(pairs,function(x) x$Name=='A'));
## [1] TRUE

If you want the number of list components that have Name=='A':

sum(sapply(pairs,function(x) x$Name=='A'));
## [1] 1

If you want the Value of the list component(s) that have Name=='A':

unlist(lapply(pairs,function(x) if (x$Name=='A') x$Value));
## [1] 11

If you want the sublist of components that have Name=='A':

pairs[sapply(pairs,function(x) x$Name=='A')];
## [[1]]
## [[1]]$Name
## [1] "A"
##
## [[1]]$Value
## [1] 11

If you want the first inner list that has Name=='A' (can drop the [1] if you're certain there will only be one match):

pairs[[which(sapply(pairs,function(x) x$Name=='A'))[1]]];
## $Name
## [1] "A"
##
## $Value
## [1] 11

Alternatively, since your data appears to be regular, you can convert to a data.frame, which will simplify all these operations:

df <- do.call(rbind,lapply(pairs,as.data.frame));
df;
##   Name Value
## 1    A    11
## 2    B    17
## 3    C    23

Here are the equivalents for df:

any(df$Name=='A');
## [1] TRUE
sum(df$Name=='A');
## [1] 1
df$Value[df$Name=='A'];
## [1] 11
subset(df,Name=='A');
##   Name Value
## 1    A    11
subset(df,Name=='A')[1,];
##   Name Value
## 1    A    11



回答2:


You can simply use Filter if your list of lists has only one level. this will return the desired element(s):

> Filter(function(u) u$Name=='A', pairs)
#[[1]]
#[[1]]$Name
#[1] "A"

#[[1]]$Value
#[1] 11



回答3:


You can use rlist

library(rlist)
list.filter(pairs, Name=='A')
#[[1]]
#[[1]]$Name
#[1] "A"

#[[1]]$Value
#[1] 11

Also, my original version is

 sapply(pairs, function(x) x[grep('Name',names(x))]=='A') 
 # Name  Name  Name 
 # TRUE FALSE FALSE 


来源:https://stackoverflow.com/questions/31104348/how-to-check-that-element-of-a-list-of-lists-matches-a-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!