1

I have a data frame final which looks like this

     TrackIndex     Time x_position y_position
1             1   0.1034        425        171
2             1   0.1379        425        169
3             1   0.1724        427        166
.........
125          25   1.1030        462        397
126          25   1.1380        462        397
127          25   1.1720        462        397
128          25   1.2070        462        397
129          25   1.2410        461        398
130          25   1.2760        462        399
131          25   1.3100        461        399
132          25   1.3450        461        399
133          25   1.3790        460        399
134          25   1.4140        460        399
.....
268          41   1.8280        302        280
269          41   1.8620        303        279
270          41   1.8970        302        280
271          41   1.9310        302        280
272          41   1.9660        302        281
273          41   2.0000        302        281
274          41   2.0340        302        281
275          41   2.0690        302        282
276          41   2.1030        302        282
277          41   2.1380        302        282
278          41   2.1720        302        283
........

I sorted this data frame by factor "TrackIndex", and selected only the first 5 rows for each unique TrackIndex using "by" function.

finalbyfactor<-by(data = final, INDICES = final$TrackIndex, FUN = function(x) head(x, 5))

This gave me the following results

> finalbyfactor
final$TrackIndex: 1
  TrackIndex   Time x_position y_position
1          1 0.1034        425        171
2          1 0.1379        425        169
3          1 0.1724        427        166
4          1 0.2069        427        167
5          1 0.2414        427        167
----------------------------------------------------------------------------- 
final$TrackIndex: 25
    TrackIndex  Time x_position y_position
125         25 1.103        462        397
126         25 1.138        462        397
127         25 1.172        462        397
128         25 1.207        462        397
129         25 1.241        461        398
----------------------------------------------------------------------------- 
final$TrackIndex: 41
    TrackIndex  Time x_position y_position
268         41 1.828        302        280
269         41 1.862        303        279
270         41 1.897        302        280
271         41 1.931        302        280
272         41 1.966        302        281

Now I want to recombine the selected rows into one data frame as the initial one. How can I do it? I tried rbind and merge, both did not work.

Xinlu Liu
  • 13
  • 4

0 Answers0