跟踪嵌套列表中的父列表

时间:2019-04-17 23:13:06

标签: r loops nested

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

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")

1 个答案:

答案 0 :(得分: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”。如果它们都是列表,则在最后一个列表中添加“测试”。