我将尝试从嵌套列表中提取向量,基于相同嵌套列表中的另一个变量或元素的值。希望我的示例可以解释我的意图。
首先,我有一个类似以下的列表嵌套列表:
如您所见,嵌套列表中的一些左侧和右侧元素包含元素
我想做的是,如果特定的嵌套列表包含元素
例如,手动创建上述示例的期望输出将类似于:
首先,我有一个类似以下的列表嵌套列表:
## Create the inner lists
# Inner list 1
listInner1 <- list(
value = c(0.25),
index = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
left = c(),
right = c()
)
listInner1$left$index <- c(1, 2, 3, 4, 5)
listInner1$left$good <- TRUE
listInner1$right$index <- c(6, 7, 8, 8, 10)
listInner1$right$good <- TRUE
# Inner list 2
listInner2 <- list(
value = c(1.5),
index = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
left = c(),
right = c()
)
listInner2$left$index <- c(1, 2, 3)
listInner2$left$good <- TRUE
listInner2$right$index <- c(4, 5, 6, 7, 8, 9, 10)
listInner2$right$good <- TRUE
# Inner list 3
listInner3 <- list(
value = c(0.5),
index = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
left = c(),
right = c()
)
listInner3$left$index <- c(1, 2, 3, 4, 5)
listInner3$right$index <- c( 6, 7, 8, 9, 10)
listInner3$left$left$index <- c(2, 4, 6, 8, 10)
listInner3$left$right$index <- c(1, 3, 5 ,7, 9)
listInner3$left$left$good <- TRUE
listInner3$left$right$good <- TRUE
# put all inner lists into single list object
listMiddle <- list(listInner1, listInner2, listInner3)
# one more list for fun
listMaster <- list(listMiddle)
如您所见,嵌套列表中的一些左侧和右侧元素包含元素
good = TRUE
,而另一些则不包含。我想做的是,如果特定的嵌套列表包含元素
good = TRUE
,则从该嵌套列表中提取元素index
。例如,手动创建上述示例的期望输出将类似于:
ans <- list(
index.1 = c(1, 2, 3, 4, 5),
index.2 = c(6, 7, 8, 8, 10),
index.3 = c(1, 2, 3),
index.4 = c(4, 5, 6, 7, 8, 9, 10),
index.5 = c(2, 4, 6, 8, 10),
index.6 = c(1, 3, 5 ,7, 9)
)
对象ans
包含所有嵌套列表中包含good = TRUE
的index
向量。
您有什么建议可以帮助我实现这个功能吗?
rrapply
内部完成。我还没有尝试过太多,但我希望它更容易。 - akrun