Reputation: 3407
I have a data.frame like this:
a b
1 1 2
2 1 3
3 2 3
4 2 5
It's sorted by a
and I need the indices of different a
's. Now I'm using for loop, however it's not elegant.
Upvotes: 0
Views: 92
Reputation: 55420
Try the following:
# this will give you the row indices
lapply(unique(dat$a), function(a) which(dat$a==a))
If you want your results to be named, use:
U <- unique(dat$a)
names(U) <- U
lapply(U, function(a) which(dat$a==a))
# Produces:
# $`1`
# [1] 1 2
#
# $`2`
# [1] 3 4
Upvotes: 2