Working with dictionaries/lists in R
Yes, the list
type is a good approximation. You can use names()
on your list to set and retrieve the 'keys':
> foo <- vector(mode="list", length=3)
> names(foo) <- c("tic", "tac", "toe")
> foo[[1]] <- 12; foo[[2]] <- 22; foo[[3]] <- 33
> foo
$tic
[1] 12
$tac
[1] 22
$toe
[1] 33
> names(foo)
[1] "tic" "tac" "toe"
>
You do not even need lists if your "number" values are all of the same mode. If I take Dirk Eddelbuettel's example:
> foo <- c(12, 22, 33)
> names(foo) <- c("tic", "tac", "toe")
> foo
tic tac toe
12 22 33
> names(foo)
[1] "tic" "tac" "toe"
Lists are only required if your values are either of mixed mode (for example characters and numbers) or vectors.
For both lists and vectors, an individual element can be subsetted by name:
> foo["tac"]
tac
22
Or for a list:
> foo[["tac"]]
[1] 22
To extend a little bit answer of Calimo I present few more things you may find useful while creating this quasi dictionaries in R:
a) how to return all the VALUES of the dictionary:
>as.numeric(foo)
[1] 12 22 33
b) check whether dictionary CONTAINS KEY:
>'tic' %in% names(foo)
[1] TRUE
c) how to ADD NEW key, value pair to dictionary:
c(foo,tic2=44)
results:
tic tac toe tic2
12 22 33 44
d) how to fulfill the requirement of REAL DICTIONARY - that keys CANNOT repeat(UNIQUE KEYS)? You need to combine b) and c) and build function which validates whether there is such key, and do what you want: e.g don't allow insertion, update value if the new differs from the old one, or rebuild somehow key(e.g adds some number to it so it is unique)
e) how to DELETE pair BY KEY from dictionary:
foo<-foo[which(foo!=foo[["tac"]])]