How can I check that an element of a list of lists matches a condition?

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 the list paris

contains an element with Name == "A"? And I would also like to receive this item.

+4


source to share


4 answers


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

      

+8


source


You can simply use Filter

if your list

of lists

only has one level. this will return the element (s) you want:



> Filter(function(u) u$Name=='A', pairs)
#[[1]]
#[[1]]$Name
#[1] "A"

#[[1]]$Value
#[1] 11

      

+4


source


you can use rlist

library(rlist)
list.filter(pairs, Name=='A')
#[[1]]
#[[1]]$Name
#[1] "A"

#[[1]]$Value
#[1] 11

      

Also, my original version

 sapply(pairs, function(x) x[grep('Name',names(x))]=='A') 
 # Name  Name  Name 
 # TRUE FALSE FALSE 

      

+2


source


Is there a way to find the position of an element in a list that has a name == "A"? Is this the first item from the list of pairs or the 2nd item?

0


source







All Articles