Andreas
Andreas

Reputation: 7550

How to make a vector-to-object lookup/hash table?

I want to store an object with a number vector as key in some data structure, such that I can later retrieve that object when I supply the data structure with an identical vector. How can I do that?

All vectors have the same number of elements. The number of objects that will be stored is low (<20).

Something like:

hash[c(1,2,4)] <- myObject

Upvotes: 1

Views: 488

Answers (1)

flodel
flodel

Reputation: 89097

You could use a list and turn your vector key into a unique character key, using paste for example:

hash <- list()
hash[[paste(c(1,2,4), collapse = '.')]] <- 1:10
hash
# $`1.2.4`
#  [1]  1  2  3  4  5  6  7  8  9 10

Same idea for retrieving the object:

hash[[paste(c(1,2,4), collapse = '.')]]
#  [1]  1  2  3  4  5  6  7  8  9 10

Upvotes: 3

Related Questions