简体   繁体   English

基于另一个向量中的索引组合列表中的元素

[英]Combine elements in list based on indexes in another vector

Given a list (a) and a numeric vector (b) of the same length as a: 给定一个列表(a)和一个长度与a相同的数字向量(b):

a <- list(1, c(3, 7), 5)
b <- c(1,1,2)

How to create a new list of length max(b) where every element in a is put in the corresponding index according to b and combined if multiple occurrences occur, so that you get: 如何创建一个长度为max(b)的新列表,其中a中的每个元素都根据b放入相应的索引中,如果出现多次,则组合起来,这样就得到:

[[1]]
[1] 1 3 7

[[2]]
[1] 5

This should hopefully be done very efficiently (no loops), as the dimensions of my data tends to be very big... 希望这可以非常有效地完成(没有循环),因为我的数据的维度往往非常大......

I'm quite sure there is an obvious solution I haven't thought about... 我很确定有一个明显的解决方案我没想过......

Thanks for the help 谢谢您的帮助

What about: 关于什么:

split(unlist(a), rep(b, sapply(a, length)))
$`1`
[1] 1 3 7

$`2`
[1] 5

Here's another way 这是另一种方式

> lapply(split(a, b), unlist)
$`1`
[1] 1 3 7

$`2`
[1] 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM