Access list element based on attribute value

  • A+
Category:Languages

Say I have a list whose elements have attributes, as below:

my_list <- list()  my_list[[1]] <- 1:10 my_list[[2]] <- 11:20 my_list[[3]] <- 21:30  attr(my_list[[1]], "att1") <- "a" attr(my_list[[2]], "att1") <- "b" attr(my_list[[3]], "att1") <- "c"  attr(my_list[[1]], "att2") <- "1" attr(my_list[[2]], "att2") <- "2" attr(my_list[[3]], "att2") <- "3" 

Now, pretend this list is many hundreds of elements long, and I don't know a priori which element of the list has the attributes I want. But I know that I want the element, with say, att1 == "b" and att2 == "2" (but where I don't know that it happens to correspond to list element 2).

Is there a way in R to look up which element(s) in a list has a particular combination of attributes?


You can filter a list with Filter:

Filter(function(x) attr(x, "att1") == "b" & attr(x, "att2") == "2", my_list) 

If you expect the element to be unique and want to select it, add [[1]] on the end.


Personally, I'd put the data into a table:

library(data.table) myDT = data.table(   att1 = sapply(my_list, attr, "att1"),    att2 = sapply(my_list, attr, "att2"),   data = my_list )  #    att1 att2               data # 1:    a    1       1,2,3,4,5,6, # 2:    b    2 11,12,13,14,15,16, # 3:    c    3 21,22,23,24,25,26, 

Then you can verify that att1 + att2 uniquely pin down an element

nrow(myDT) == uniqueN(myDT, by=c("att1", "att2")) # [1] TRUE 

and write a helper function for subsetting

setkey(myDT, att1, att2) get_element = function(a1, a2) myDT[.(a1, a2), data[[1]]]  get_element("b", "2") #  [1] 11 12 13 14 15 16 17 18 19 20 # attr(,"att1") # [1] "b" # attr(,"att2") # [1] "2" 

You might also want to look at the purrr and broom packages, which offer different, "tidyverse" syntax for tables with a list column.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: