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",".")
match(X,Y)
#> [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")
iwr$B[get_index("water")]
#> [1] 0
iwr$C[get_index("water")]
#> [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}
.