How can you access the name of a list element within a function if you pass not the whole list but only the list element (dataframe)?
I have a named list of dataframes, e.g.
files <- list(BRX = -0.72, BRY = -0.72, BRZ = -0.156, BTX = -0.002, BTY = -0.002,
BTZ = -0.0034)
Later in the code, I will use a single list element as input for a plot function. This plot function shall also print the list element's name. How can I access it?
I have the following solution - it works but is a bit cumbersome:
map2(files, names(files),
function(file, filename) {
data.table::setattr(file, "filename", filename)
})
Later, I can retrieve the filename as attribute within the plot function by:
plotfunction(list_element, ...) {
...
filename <- attr(input, "filename")
...
+ ggtitle(filename)
...
}
Is there a more elegant alternative solution, either by a different way to access the list element name, or by setting the filename attribute differently?