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.
There are 2 ways to understand check if the list contains elements of another list. First, use all() functions to check if a Python list contains all the elements of another list. And second, use any() function to check if the list contains any elements of another one.
Use the any() function to check if any element in a list meets a condition, e.g. if any(item > 10 for item in my_list): . The any function will return True if any element in the list meets the condition and False otherwise.
Python all() Function The all() function returns True if all items in an iterable are true, otherwise it returns False.
You can convert the list to a set. A set cannot have duplicates. So if all the elements in the original list are identical, the set will have just one element. if len(set(input_list)) == 1: # input_list has all identical elements.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With