How can I check that an element of a list of lists matches a condition?
If you just want to know if any component of the list has Name=='A'
:
any(sapply(pairs,function(x) x$Name=='A'));
## [1] TRUE
If you want the number of list components having Name=='A'
:
sum(sapply(pairs,function(x) x$Name=='A'));
## [1] 1
If you want a Value
list (s) of a list that has Name=='A'
:
unlist(lapply(pairs,function(x) if (x$Name=='A') x$Value));
## [1] 11
If you want a 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 to have Name=='A'
(can drop [1]
if you are sure 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 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
source to share