3

我为这个有点混乱的标题道歉(欢迎任何改进建议)..

假设我有一个列表,其中包含几个(例如四个)列表,稍后我想在其中存储 20 个对象:

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)

我想事先定义这些对象的名称。当然,我可以这样做:

 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) 

但是如果列表的数量会增加(就像我的实际数据一样),这会变得相当麻烦,所以我试图用一个函数来做到这一点,例如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")})

然而,这并没有给我同样的结果,但我似乎无法弄清楚我在这里忽略了什么。有什么建议么?

谢谢!

4

2 回答 2

3

您需要在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")
                    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" 
于 2013-09-13T14:21:06.657 回答
2

这是我的实现,我认为它会产生您期望的结果

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
于 2013-09-13T15:22:12.747 回答