Home > Software engineering >  Group list elements
Group list elements

Time:01-05

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

CodePudding user response:

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

CodePudding user response:

Using split

lapply(split(l, g), unlist)
$A
[1] 3 4 7 8

$B
[1]  8  9 10

Or get the lengths and split after unlisting

 split(unlist(l), rep(g, lengths(l)))
$A
[1] 3 4 7 8

$B
[1]  8  9 10
  • Related