问题
Or put it more general: How can I add multiple attributes to the elements of list?
I am stuck trying to set an attribute to elements of a list all of which are data.frames
. In the end I would like to add names(myList)
as a varying attribute to every data.frame
inside. But I even cannot get a static attribute for all list elements to go.
lapply(myList,attr,which="myname") <- "myStaticName"
This does not work because lapply
does not work with lapply<-
. If I had at least an idea how to do this, maybe I could figure out how to do it with varying attributes like the name of the list.
回答1:
I don't recommend it, but you could do: lapply(myList, 'attr<-', which='myname', value='myStaticName')
. An old fashioned for
loop is probably the clearest way to perform this task---or do this assignment upstream when the objects are created.
for (i in seq_along(myList)) attr(myList[[i]], 'myname') <- 'myStaticName'
EDIT:
As @mnel points out in the comments, setattr
in the data.table
package is also an efficient option, since it assigns by reference.
Edit: @mnel -- don't use setattr with lapply
. This is one case where the for
loop is much faster.
library(microbenchmark)
library(data.table)
myList <- as.list(1:10000)
`lapply.attr<-` <-
function()
lapply(myList, 'attr<-', which='myname', value='myStaticName')
`for.attr<-` <-
function()
for (i in seq_along(myList))
attr(myList[[i]], 'myname') <- 'myStaticName'
lapply.setattr <-
function()
lapply(myList, setattr, name='myname', value='myStaticName')
for.setattr <- function()
for (i in seq_along(myList))
setattr(myList[[i]], name = 'myname', value = 'myStaticName')
result <- microbenchmark(`lapply.attr<-`(), `for.attr<-`(), lapply.setattr(), for.setattr())
plot(result)

回答2:
Based on this answer by Thierry I found a solution on my own. Actually I have been close with several tries but did not return the WHOLE list which is key.
myList <- lapply(names(myList),function(X){
attr(myList[[X]],"myname") <- X
myList[[X]]
})
My mistake was not to return the whole list but only the second line of the function, i.e. the attribute. Thus I was not able to replace the initial list.
@Matthew Plourde: what's strange: your benchmark looks somewhat different on my machine: RStudio, OS X, 2.5 Ghz Intel Core i7, 16GB RAM.

来源:https://stackoverflow.com/questions/13614399/how-can-i-use-attr-with-lapply