跟踪嵌套列表中的父列表

问题描述 投票:1回答:1

我有一个我需要迭代的嵌套循环。我想转到列表的末尾(在这种情况下是父列表的第二项),如果它不再是嵌套循环,则添加项目。因此循环可能有许多级别的嵌套循环。现在,我只获得第二个名单作为回报。如何跟踪父列表?

a <- list( x = list(1,2,3),y =list(4,5,6))
 con=TRUE
 while(con){
 i <-length(a)
 for(k in i:i){
 if(!typeof(a[[k]])=="list"){
   a[[k+1]] <- "test"
   con=FALSE
  }else{
  a <- a[[k]]
   i <- length(a)
 }
 }
}


Expected Result:a <- list(x = list(1,2,3), y =list(4,5,6, "test"))
Result: a <- list(4,5,6,"test")
r loops nested
1个回答
0
投票
library(magrittr)
a <- list( x = list(1,2,3),y =list(4,5,6), z = 1)

temp <- lapply(a, typeof) %>% unlist
tempList <- (temp!="list")

if (sum(tempList) > 0) {
  a[[max(which(tempList == FALSE))]] %<>% append("test")
} else {
  a[[length(a)]] %<>% append("test")
}

我不清楚你想要做什么,但只关注你的例子,这会奏效。

简而言之,看看父列表的哪些元素不是列表,并且为最后一个元素添加“test”。如果所有这些都是列表,则将“test”添加到最后一个列表中。

© www.soinside.com 2019 - 2024. All rights reserved.