Search code examples
rlistgrouping

How to group list elements according to groups defined in a grouping vector?


Consider a list and a grouping vector

l = list(3:4, 8:10, 7:8)
# [[1]]
# [1] 3 4
# 
# [[2]]
# [1]  8  9 10
# 
# [[3]]
# [1] 7 8

g = c("A", "B", "A")

What is the easiest way to group l elements according to groups defined in g, such that we get:

l_expected = list(c(3:4, 7:8), 8:10))
# [[1]]
# [1] 3 4 7 8
# 
# [[2]]
# [1]  8  9 10

Solution

  • One way is to use tapply + unlist, and unname if necessary.

    tapply(l, g, unlist)
    

    output

    $A
    [1] 3 4 7 8
    
    $B
    [1]  8  9 10