如何检查列表列表中的元素是否符合条件? [英] How to check that element of a list of lists matches a condition?
问题描述
我有一个列表列表:
pairs <- list(
list(Name="A",Value=11),
list(Name="B",Value=17),
list(Name="C",Value=23)
)
如何检查 pairs
列表中是否包含Name =="A"的元素?而且我也想获得该元素.
How can I check that pairs
list contains an element with Name=="A"?
And I'd also like to get that element.
推荐答案
如果您只想知道任何列表组件是否具有 Name =='A'
:
If you just want to know whether any list component has Name=='A'
:
any(sapply(pairs,function(x) x$Name=='A'));
## [1] TRUE
如果要具有 Name =='A'
的列表组件的数量:
If you want the number of list components that have Name=='A'
:
sum(sapply(pairs,function(x) x$Name=='A'));
## [1] 1
如果要具有 Name =='A'
的列表组件的 Value
:
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
如果要具有 Name =='A'
的组件的子列表:
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
如果您想要第一个具有 Name =='A'
的内部列表(如果确定只有一个匹配项,则可以删除 [1]
):
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
或者,由于您的数据看起来很规则,因此您可以转换为data.frame,这将简化所有这些操作:
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
以下是 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
这篇关于如何检查列表列表中的元素是否符合条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!