rose
rose

Reputation: 1981

Creating a new list by combining element of previous list in R

I have a list something like this:

    v = list(a1= 1, a2 = 2, b1 = 3, b2= 4, b3 = 5)

my desire result is creating a list something like this :

   v = list(a = c(1, 2), b = c(3, 4, 5))

But it should be mentioned that vector v is my exapmle, I can wrote the code for above example, but my problem is that if each time the length of ai and biis different, how can wrote a function to get my desire result in R?

Upvotes: 1

Views: 80

Answers (2)

flodel
flodel

Reputation: 89057

split(unlist(v), sub("\\d+$", "", names(v)))
# $a
# a1 a2 
#  1  2 
# 
# $b
# b1 b2 b3 
#  3  4  5 

Upvotes: 2

Tyler Rinker
Tyler Rinker

Reputation: 109874

I'm sure there's a more clever way but here's one approach with regex:

starters <- letters[1:2]
v2 <- lapply(starters,  function(x) {
    unname(unlist(v[grepl(x, names(v))]))
})

names(v2) <- starters

## $a
## [1] 1 2
## 
## $b
## [1] 3 4 5

Upvotes: 2

Related Questions