0

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.

3

1 Answer 1

2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.