Search code examples
rfunctionindexingunique

indexing/linking rows to a unique identifier


My data:

id<-c(1,1,1,1,1,1,1,2,2,2)
start<-c(0,1,3,5,7,8,10,0,0,1)
end<-c(1,3,5,7,8,9,12,0,1,4)
mydata<-data.frame(id,start,end)

Question:

What code would I use to indicate that rows 1-7 are linked to the unique id(1), and rows 8-10 are linked to id(2)? The output should look as follows:

Indexes[1:2]
$ '1'
1 2 3 4 5 6 7
$ '2'
8 9 10`

Attempt:

I have looked around StackOverflow but don't really see this being done. I did try

split(mydata,mydata$id)

I know that if I say:

which(mydata$id==1)

It will tell me rows 1-7. But don't know how to use this to my advantage to get the output above.

but that certainly doesn't work.


Solution

  • You were almost there. split can be used on the rownames as well. Since they'll be character values, you coerce them to numeric with as.numeric

    > Indexes <- split(as.numeric(rownames(mydata)), mydata$id)
    > Indexes[1:2]   ## or just 'Indexes' for your sample data
    ## $`1`
    ## [1] 1 2 3 4 5 6 7
    
    ## $`2`
    ## [1]  8  9 10