gpt4 book ai didi

R:如何以原始顺序获取列表列表的名称?

转载 作者:行者123 更新时间:2023-12-02 17:30:07 25 4
gpt4 key购买 nike

我想获取列表列表的名称。因此,我想将列表元素(第一级)的名称与列表元素列表(第二级)的名称粘贴(或添加)。这应该用“.”来完成。对我来说重要的是让名称的顺序与列表列表中的顺序相同。这是一个没有值的示例(请注意,我有更多的子列表,因为每个元素有九个):

GER_WF_groups <- list(A=list(fruits.2000=matrix(),nuts.2000=matrix(),veggies.2000=matrix(),
fruits.2001=matrix(),nuts.2001=matrix(),veggies.2001=matrix(),
fruits.2002=matrix(),nuts.2002=matrix(),veggies.2002=matrix()),
B=list(fruits.2000=matrix(),nuts.2000=matrix(),veggies.2000=matrix(),
fruits.2001=matrix(),nuts.2001=matrix(),veggies.2001=matrix(),
fruits.2002=matrix(),nuts.2002=matrix(),veggies.2002=matrix()),
C=list(fruits.2000=matrix(),nuts.2000=matrix(),veggies.2000=matrix(),
fruits.2001=matrix(),nuts.2001=matrix(),veggies.2001=matrix(),
fruits.2002=matrix(),nuts.2002=matrix(),veggies.2002=matrix()))

直到我知道我使用了一种复杂的方法来获取这个有序名称,但它确实有效,请参见下文:

years_sapply2 <- sapply(GER_WF_groups,function(x) paste("BLUE", names(x) ,sep="."))
str(years_sapply2)
years_mat2 <- matrix(years_sapply2, nrow=9, byrow=F)
years_mat3 <- matrix(years_mat2, ncol=1, byrow=F)
years_vec <- years_mat3[,1]
BLUEyears <- years_vec[1:9]
GREENyears <- BLUEyears
GREYyears <- BLUEyears
GREENyearsN <- sub("BLUE", "GREEN", GREENyears)
GREYyearsN <- sub("BLUE", "GREY", GREYyears)
years_namesALL <- c(BLUEyears, GREENyearsN, GREYyearsN)

我的问题是:是否有更快/更简单的方法来完成这项工作?谢谢

"years_namesALL"是预期的结果。

最佳答案

Vongo 方法的变体如下所示:

names(unlist(setNames(GER_WF_groups, c("BLUE", "GREEN", "GREY"))))
## [1] "BLUE.fruits.2000" "BLUE.nuts.2000" "BLUE.veggies.2000"
## [4] "BLUE.fruits.2001" "BLUE.nuts.2001" "BLUE.veggies.2001"
## [7] "BLUE.fruits.2002" "BLUE.nuts.2002" "BLUE.veggies.2002"
## [10] "GREEN.fruits.2000" "GREEN.nuts.2000" "GREEN.veggies.2000"
## [13] "GREEN.fruits.2001" "GREEN.nuts.2001" "GREEN.veggies.2001"
## [16] "GREEN.fruits.2002" "GREEN.nuts.2002" "GREEN.veggies.2002"
## [19] "GREY.fruits.2000" "GREY.nuts.2000" "GREY.veggies.2000"
## [22] "GREY.fruits.2001" "GREY.nuts.2001" "GREY.veggies.2001"
## [25] "GREY.fruits.2002" "GREY.nuts.2002" "GREY.veggies.2002"

如果只有一层嵌套,可以尝试:

names(unlist(setNames(GER_WF_groups, c("BLUE", "GREEN", "GREY")), recursive = FALSE))

关于R:如何以原始顺序获取列表列表的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34437427/

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