Pergunta

My apologies for the somewhat confusing title (any suggestion for improvement are welcome)..

Suppose I have a list which contains several (e.g. four) lists in which I would like to store 20 objects later on:

mylist <- vector(mode="list",length=4)
names(mylist) <- c("One","Two","Three","Four")
mylist$One <- mylist$Two <- mylist$Three <- mylist$Four <- vector(mode="list",
                                                                  length=20)

I would like to define the names of those objects beforehand. Of course, I can do that as following:

 names(mylist$One) <- c("A","B","C","D","E","F","G","H","I","J",
                        "K","L","M","N","O","P","Q","R","S","T")

 names(mylist$Two) <- names(mylist$Three) <- names(mylist$Four) <- names(mylist$One) 

But if the number of the lists would increase (as is the case in my actual data), this becomes rather cumbersome, so I was trying to do this with a function such as lapply :

mylist <- lapply(mylist,FUN=function(x) {names(x) <-   
                        c("A","B","C","D","E","F","G","H","I","J",
                          "K","L","M","N","O","P","Q","R","S","T")})

This, however, does not give me the same result, but I can not seem to figure out what I am overlooking here. Any suggestions?

Thanks!

Foi útil?

Solução

You need to return a value in your lapply call:

mylist <- lapply(mylist,FUN=function(x) {names(x) <-   
                    c("A","B","C","D","E","F","G","H","I","J",
                      "K","L","M","N","O","P","Q","R","S","T")
                    x ## <- note the x here; you could also use return(x)
})

mylist
# $One
#   A   B   C   D   E   F   G   H   I   J   K   L   M   N   O   P   Q   R   S   T 
# "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" 
# 
# $Two
#   A   B   C   D   E   F   G   H   I   J   K   L   M   N   O   P   Q   R   S   T 
# "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" 
# 
# $Three
#   A   B   C   D   E   F   G   H   I   J   K   L   M   N   O   P   Q   R   S   T 
# "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" 
# 
# $Four
#   A   B   C   D   E   F   G   H   I   J   K   L   M   N   O   P   Q   R   S   T 
# "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" 

Outras dicas

This is my implementation, which I think it produces the results you are expecting

mylist <- vector(mode="list",length=4)
names(mylist) <- c("One","Two","Three","Four")
mylist$One <- mylist$Two <- mylist$Three <- mylist$Four <- vector(mode="list",length=20)

renameList <- function(mylist,k){
    names(mylist) <-  LETTERS[1:k]
    return(mylist)
}

mylist2 <- lapply(mylist, function(x) renameList(x,20))

# > str(mylist2)
# List of 4
#  $ One  :List of 20
#   ..$ A: NULL
#   ..$ B: NULL
#   ..$ C: NULL
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top