This is an old revision of the document!


Dictionaries in R

Dictionary is a data structure containing pairs (key, value) providing fast (usually constant time) access to a value corresponding to a given key. Dictionary data structure is available in most modern high level programming languages. In R they are not provided explicitly, but can be implemented using environments.

As an example, consider a list of cows K. Their names are keys. To each name we assign a value with two components: index i and repetition count n combined into a list. If necessary additional components can be included in the list.

> K <- c("Liska", "Šeka", "Bistra", "Sivka", "Liska", "Cika", "Belka", "Liska", "Sivka", "Pika")
> ime <- new.env(hash=TRUE,parent=emptyenv())
> for(k in K){
+     if (exists(k,env=ime,inherits=FALSE)){
+         d <- get(k,env=ime,inherits=FALSE)
+         ik <- d$i; nk <- d$n+1
+         assign(k,list(i=ik,n=nk),env=ime)
+     } else {
+         ik <- length(ls(ime))+1; nk <- 1
+         assign(k,list(i=ik,n=nk),env=ime)
+     }
+     cat(format(k,width=8),ik,nk,"\n")
+ }
Liska    1 1 
Šeka     2 1 
Bistra   3 1 
Sivka    4 1 
Liska    1 2 
Cika     5 1 
Belka    6 1 
Liska    1 3 
Sivka    4 2 
Pika     7 1 

In the case when we need only the index of a given cow k we can (write and) use the function kInd(k):

> kInd <- function(k) return(if(exists(k,env=ime,inherits=FALSE)) get(k,env=ime,inherits=FALSE)$i else NA)
> kInd("Sivka")
[1] 4
> kInd("Hator")
[1] NA

URLs

notes/net/edic.1505390521.txt.gz · Last modified: 2017/09/14 14:02 by vlado
 
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki