Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

list

r

match

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.

like image 867
Pavel Voronin Avatar asked Jun 28 '15 20:06

Pavel Voronin


People also ask

How do you check if an element of a list is in another list?

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.

How do you check if any element of a list satisfies a condition in Python?

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.

How do you check if every element in a list is true?

Python all() Function The all() function returns True if all items in an iterable are true, otherwise it returns False.

How do you check if all elements in a list are equal Python?

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.


1 Answers

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
like image 159
bgoldst Avatar answered Sep 22 '22 18:09

bgoldst