Created
November 8, 2019 04:21
-
-
Save goldingn/26da37af5862dab7cae7a3561e362bd9 to your computer and use it in GitHub Desktop.
playing with letting R objects know their own names
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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