andilabs
9/17/2013 - 3:10 AM

dictionary in R

dictionary in R

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 dictionaris in R:

a) how to return all the values:

    >as.numeric(foo)
    [1] 12 22 33

b) chech whether dict contains key:

  >'tic' %in% names(foo)
	[1] TRUE

c) how to add key, value piar to dictionary:
	>c(foo,tic2=44)
	tic       tac       toe 	tic2
    12        22        33        44 

d) how to fullfil the requirment of REAL DICTIONARY - thath keys CAN NOT repeat? You need to combine b) and c) and build function which validates whethere 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"]])]
	> foo
tic toe 
 12  33