Skip to content

Instantly share code, notes, and snippets.

@goldingn
Created November 8, 2019 04:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goldingn/26da37af5862dab7cae7a3561e362bd9 to your computer and use it in GitHub Desktop.
Save goldingn/26da37af5862dab7cae7a3561e362bd9 to your computer and use it in GitHub Desktop.
playing with letting R objects know their own names
# how to make R objects know their own names?
# this works with commands run in the global environment, but not inside functions
this_call <- function() {
file1 <- tempfile("Rrawhist")
savehistory(file1)
rawhist <- readLines(file1)
rawhist[length(rawhist)]
}
my_name <- function () {
expr <- parse(text = this_call())[[1]]
if (length(expr) != 3) {
return(NULL)
}
as.character(expr[[2]])
}
new_object <- function() {
list(my_name_is = my_name())
}
x <- new_object()
x
# $my_name_is
# [1] "x"
blah <- function() {
x <- new_object()
x
}
blah()
# $my_name_is
# NULL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment