Skip to content

Instantly share code, notes, and snippets.

@ConradStack
Created June 11, 2016 16:30
Show Gist options
  • Save ConradStack/9a8b10d771c2e4054a499c369cbe66d5 to your computer and use it in GitHub Desktop.
Save ConradStack/9a8b10d771c2e4054a499c369cbe66d5 to your computer and use it in GitHub Desktop.
Adding metadata to R files
##
## From http://www.r-bloggers.com/adding-metadata-to-variables/
##
# add a comment to a variable (NB -> comment(...) function is base R)
# example
xx <- 1:10
comment(xx) <- "one through ten"
attributes(xx)
comment(xx) <- "another one" # NB -> adding another comment overwrites the last one
attributes(xx)
# Get current user
get_user <- function()
{
env <- if(.Platform$OS.type == "windows") "USERNAME" else "USER"
unname(Sys.getenv(env))
}
# Add some metadata to a variable before assignment (a wrapper for assign(...))
assign_with_metadata <- function(x, value, ..., pos = parent.frame(), inherits = FALSE)
{
attr(value, "creator") <- get_user()
attr(value, "time_created") <- Sys.time()
more_attr <- list(...)
attr_names <- names(more_attr)
for(i in seq_along(more_attr))
{
attr(value, attr_names[i]) <- more_attr[[i]]
}
assign(x, value, pos = pos, inherits = inherits)
}
assign_with_metadata("x", 1:3, monkey = "chimp") # example
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment