Link
Link

Reputation: 51

Creating a list in R from 2 vectors

I have a problem when I try to create a list in R. I have 2 vectors

a <- c(1:7)
b <- c("A", "A", "B", "B", "B", "C", "C")

The second vector (b) is an ordered factor. I am trying to create a list that would have the following form:

[A]
1, 2

[B]
3, 4, 5

[C]
6, 7

ie. I want to put the elements of the first vector into a list with each block of the list corresponding to the factor level of the second vector. I hope I was clear enough, thank you

Upvotes: 1

Views: 204

Answers (1)

David Arenburg
David Arenburg

Reputation: 92282

Seems you could just use split here

split(a, b)
# $A
# [1] 1 2
# 
# $B
# [1] 3 4 5
# 
# $C
# [1] 6 7

Upvotes: 3

Related Questions