使用R从另一个列表中的索引中提取列表中的元素 [英] Extract elements from a list using indexes from another list using R

查看:85
本文介绍了使用R从另一个列表中的索引中提取列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含向量集合的列表和另一个(相同长度的)索引列表.我想使用第二个列表仅提取第一个列表的索引元素.

I have a list with collections of vectors and a second list (of the same length) of indexes. I'd like to use the second list to extract only the indexed elements of the first list.

dataList <- list(1:10, 101:150, LETTERS)
indexList <- list(3:5, 10:15, c(1,5,9,15,21))

即我想要一个函数来返回一个与dataList相同长度的新列表,但只包含由indexList索引的成员.

i.e. I'd like a function to return a new list the same length as dataList, but containing only the members indexed by indexList.

推荐答案

我们可以使用Map基于'indexList'的索引提取相应的list元素

We can use Map to extract the corresponding list elements based on the index from 'indexList'

Map(`[`, dataList, indexList)


或使用purrr

library(purrr)
map2(dataList, indexList, `[`)

这篇关于使用R从另一个列表中的索引中提取列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆