gpt4 book ai didi

r - 在列表中的多个列表中定义对象的名称(使用 lapply?)

转载 作者:行者123 更新时间:2023-12-01 11:42:16 25 4
gpt4 key购买 nike

我为这个有点困惑的标题道歉(欢迎提出任何改进建议)..

假设我有一个包含多个(例如四个)列表的列表,稍后我想在其中存储 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")})

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

谢谢!

最佳答案

您需要在 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"

关于r - 在列表中的多个列表中定义对象的名称(使用 lapply?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18788613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com