How to check that element of a list of lists matches a condition?
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
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
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