Home > Net >  Find the function call behind a list
Find the function call behind a list

Time:03-12

Suppose you have a list like the following:

x <- list(mtcars$mpg, mtcars$cyl)

You just have access to x, you don't know what was the function call that created x. Is there a way to obtain the call that created x?

In other words, is it possible to pass x in a function and to obtain list(mtcars$mpg, mtcars$cyl)? (I'm trying to obtain mtcars$mpg and mtcars$cyl, it doesn't matter if they are in a list or not).

CodePudding user response:

If you have a standard list without names, the history of its creation is not stored as part of the object.

All R objects represent an underlying C structure called an SEXP, which is a pointer to the data-storing object (the SEXPREC) along with a flag indicating the type of object. The SEXPREC of plain R lists, as in your example, are stored as three pointers (previous node, next node, and pointer to attributes such as names), followed by a block of pointers to the data objects stored in the list. The call that created the list is not stored anywhere within this structure. It is possible to create a list that has this information stored specifically as a data member or attribute, but it is not stored routinely in normal lists. See here for more information about the underlying data structure.

I'm very cautious about giving an answer that says something can't be done, and it may be possible in some circumstances to find which objects in the current session share memory with the list object, but I would assert that it is not possible in general.

If you want to create a list that contains the memory of how it was created, you could do something like this:

list_mem <- function(...) {
  
  val <- list(...)
  attr(val, "call") <- match.call()
  val
}

x <- list_mem(mtcars$mpg, mtcars$cyl)

x
#> [[1]]
#>  [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4 10.4
#> [17] 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7 15.0 21.4
#> 
#> [[2]]
#>  [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
#> 
#> attr(,"call")
#> list_mem(mtcars$mpg, mtcars$cyl)

But of course, this would have to be done specifically with this purpose in mind.

  •  Tags:  
  • r
  • Related