在R语言中从嵌套的列表中提取向量。

4
我将尝试从嵌套列表中提取向量,基于相同嵌套列表中的另一个变量或元素的值。希望我的示例可以解释我的意图。
首先,我有一个类似以下的列表嵌套列表:
## 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 = TRUEindex向量。

您有什么建议可以帮助我实现这个功能吗?

1个回答

4

这里有一个选项,我们使用rrapply将嵌套元素绑定到更容易处理的格式上,然后获取“good”列的索引,通过在map2中循环提取相应的“index”元素(基于TRUE值),transposelistkeep只保留长度大于0的元素,flattenlist并设置名称(如果需要)。

library(purrr)
library(rrapply)
library(stringr)
library(dplyr)
out <- rrapply(listMaster, how = 'bind')
i1 <- grep('good', names(out))
map2(out[i1-1], out[i1], `[`) %>%
   transpose %>%
   map( ~ keep(.x, lengths(.x) > 0)) %>%
   flatten %>%
   setNames(str_c('index.', seq_along(.)))

-输出

$index.1
[1] 1 2 3 4 5

$index.2
[1]  6  7  8  8 10

$index.3
[1] 1 2 3

$index.4
[1]  4  5  6  7  8  9 10

$index.5
[1]  2  4  6  8 10

$index.6
[1] 1 3 5 7 9

1
非常复杂的问题。你是怎么把这些都记在脑子里的? :-) - TarJae
1
@TarJae 我认为这个函数看起来很复杂,可能可以更容易地在rrapply内部完成。我还没有尝试过太多,但我希望它更容易。 - akrun
1
它完美地运行了。我试了几个小时,但一直无法理解。谢谢。 - Electrino
2
@TarJae请不要相信我是一口气完成的。 不,我没有。 只是当我尝试某件事时,我会尝试多种方式,即查找函数中是否存在任何漏洞。 其中一些可能在文档中不存在。 有些是通过试错发现的。 我认为学习的最佳方法是尝试某些东西,当您发现错误时,您会对该函数有非常独特的了解。 - akrun
@akrun,很高兴听到这个消息。所以我这样做并没有错!虽然它非常耗时,但最终你是正确的!大师请看这里https://dev59.com/JGgMtIcB2Jgan1znKH-K#69094325。你对这个答案有什么看法? - TarJae

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接