[R] Is there a hash data structure for R

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Tue Nov 2 12:54:14 CET 2021

On 02/11/2021 4:13 a.m., Yonghua Peng wrote:
> I know this is a newbie question. But how do I implement the hash structure
> which is available in other languages (in python it's dict)?
> I know there is the list, but list's names can be duplicated here.

As Eric said, the environment comes pretty close.  One difference 
between lists and environments is that environments are reference 
objects, so this changes e1$x:

   e1 <- new.env()
   e1$x <- 1
   e2 <- e1
   e2$x <- 2

Lists are not reference objects, so this doesn't change l1$x:

   l1 <- list()
   l1$x <- 1
   l2 <- l1
   l2$x <- 2

I don't know which behaviour you'd feel more comfortable with. 
Reference objects are pretty rare in R, so some R programmers would be 
surprised by the environment behaviour.  But in other languages they're 
more common, so maybe newbies would be more surprised by the list behaviour.

Another difference betwee environments and lists is how they handle 
assignments of NULL:

   e1$y <- NULL   # sets e1$y to NULL
   l1$y <- NULL   # does nothing here, would delete l1$y if it existed

I don't like the NULL handling in lists in R, but I'm used to it.

BTW, I don't understand why the possibility of duplicated names is an 
issue.  If you just avoid intentional duplication, you don't get it. 
For example, if instead of this:
>> x <- list(x=1:5,y=month.name,x=3:7)

you do this:

x <- list(x=1:5,y=month.name)
x$x <- 3:7

there is no duplication.  The only (?) ways to get duplication are in 
the initial construction of the list, or by explicit manipulation of the 
names attribute.  So be careful when you do those, and lists can work.

Duncan Murdoch

>> x
> $x
> [1] 1 2 3 4 5
> $y
>   [1] "January"   "February"  "March"     "April"     "May"       "June"
>   [7] "July"      "August"    "September" "October"   "November"  "December"
> $x
> [1] 3 4 5 6 7
> Thanks a lot.
> 	[[alternative HTML version deleted]]
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list