9

I am trying to find ways to make link list in R.

I found tracemem() returns the memory address of an object, so is there any way I can find an object by its memory address?

zx8754
  • 52,746
  • 12
  • 114
  • 209
user2961927
  • 1,290
  • 1
  • 14
  • 22

2 Answers2

7

That's not the way to do it. If you want references use Reference Classes or environments. Like this:

First, three objects I am going to put in my linked list:

> e1=new.env()
> e2=new.env()
> e3=new.env()

initialise with a data item and a pointer to the next in the list

> with(e1,{data=99;nextElem=e2})
> with(e2,{data=100;nextElem=e3})
> with(e3,{data=1011;nextElem=NA})

now a function that given an environment returns the next in the linked list:

> nextElem = function(e){with(e,nextElem)}

So lets start from some environment e:

> e=e1
> with(e,data)
[1] 99

To get the value of the next item in the list:

> with(nextElem(e),data)
[1] 100

and just to prove things are being done by reference, lets change e2:

> with(e2,{data=555})

and the next item from e has changed too:

> with(nextElem(e),data)
[1] 555

Reference classes should make this a bit cleaner, but require a bit of planning.

Trying to get R objects by their memory location is not going to work.

Spacedman
  • 92,590
  • 12
  • 140
  • 224
0

Since I found a straightforward way to do it, I'm postint it here:

This can be used to get a list of the addresses and objects, it could be manipulated to get objects by memory address

oo <- ls(envir=.GlobalEnv)
ad <- lapply(oo, function(.x) do.call(pryr::address,list(rlang::sym(.x))) ) 
setNames(ad, oo)

With a little of tidyverse you can get a nice table:

oo <- ls(envir=.GlobalEnv)
purrr::map_chr(oo, ~ do.call(pryr::address,list(rlang::sym(.x))) ) %>%
    setNames(oo) %>%
    tibble::enframe()
Bruno
  • 115
  • 1
  • 9