I am applying a function to the elements of a list.
the list has names, so in a sense each element has its own name, but how do I access it once the lapply function has already extracted/separated the element from the list?
Some fictive data (as internal function I’m here misusing dput):
r <- list(a=structure(1:4, unit="test"), b='abc')
lapply(r, dput)
What I observe here is that dput receives the objects in the list as if accessed with [[, deprived of the name they have in the containing list.
So I thought I would drop the idea of using functions from the apply family and write a loop, but I don’t particularly like the idea and it obliges me to construct the result of the complete function.
result <- list()
for (name in names(r)) {
print(name)
result[[name]] <- dput(r[[name]])
}
result
Any insightful thoughts?
You can simulate the idea behind loops whilst still using
lapply, by passing a numeric vector tolapplyand then using that as an index to extract the elements from the list you want. That probably makes no sense, but hopefully the example illustrates what I mean:The key idea is that
seq_along(x)returns a sequence of the same length asx. For example:See
?seq_alongfor more detail.EDIT
This seems to be very marginally faster than indexing by name: