how to access elements in a List

This list is created such that each element in A corresponds to elements in B and C. I would like to be able to retrieve the corresponding element in B and C by A.

and I would like to get B=0 and C=T
what I thought of doing is:
match("water", iwr) this would give 1
and then I would do: iwr$B[1], this would give 0

Please is there a more efficient way to do this? Thanks

iwr=list("A"= "fish", "meat", "water", "air", "fire", "flame", "B"= 0,0,0,1,1, "C"= T, T, T, F, F)

I had another dataset with a similar structure and I did match("water", iwr$A) and I got NA....would like to know why.. Thanks

except that only "fish" has the attribute A. That is A does not refer to the other character strings, only the first. Similarly for B and C. What iwr amounts to is a single list of 16 elements. To do lookups, it should be a list of vectors of equal size and match should not be used.

match compares two vectors, say X and Y and searches Y for each element in X and returns only the index of the first match.

X = letters
Y = c("t","h","e","","q","u","i","c","k","","b","r","o","w","n","","f","o","x","","j","u","m","p","e","d","","o","v","e","r","","t","h","e","","l","a","z","y","","d","o","g",".")
#>  [1] 38 11  8 26  3 17 44  2  7 21  9 37 23 15 13 24  5 12 NA  1  6 29 14 19 40
#> [26] 39

Created on 2022-11-27 by the reprex package (v2.0.1)

For ad hoc use here's an approach

iwr<- list(
  A = c("fish", "meat", "water", "air", "fire"), 
  B = c(0,0,0,1,1), 
  C = c(T, T, T, F, F)

# hardwired for simplification; iwr and A should be parameterized
get_index <- function(x) which(iwr$A == "water")

#> [1] 0
#> [1] TRUE

For larger datasets, it would be better to create heaps, with A as key and B and C as values. There are two packages to do this—the relatively simple {heap} and the sophisticated {datastructures}.

1 Like

It seems that you forgot to wrap the contents of A in c() or list() and same for B and C etc.
And if they by design are meant to be directly associated by position, then its just a data.frame posing as a list, so i would convert to a dataframe and use the standard tooling.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.