rdata.table360-degrees

Maximum difference in headings per group


I have a data.table with information about (360-degrees) headings per group.

library(data.table)
dt <- data.table(headings = c(340,0,20,90,180,270,91), grp = c(1,1,1,2,2,2,2))

   headings grp
1:      340   1
2:        0   1
3:       20   1
4:       90   2
5:      180   2
6:      270   2
7:       91   2

in grp 1 the distance between headings is 20, 20 and 320 and in grp 2 its 1,89,90 and 180. I would like to find the maximum distance between headings and add them to each group, so the result would look like this:

   headings grp maxHeading
1:      340   1        320
2:        0   1        320
3:       20   1        320
4:       90   2        180
5:      180   2        180
6:      270   2        180
7:       91   2        180

I don't necessarily want a data.table solution, but would be nice if there was one.

EDIT: To clarify, I changed the values and added a datapoint in grp 2. Here is also two piecharts to visualize.

For grp 1: enter image description here

For grp 2: enter image description here


Solution

  • You can calculate the diffs after sorting, adding one more for the pair crossing 0/360:

    dt[, v := max(
      diff(sort(headings)),
      min(headings) - max(headings) + 360
    ), by=grp]
    
       headings grp   v
    1:      340   1 320
    2:        0   1 320
    3:       20   1 320
    4:       90   2 180
    5:      180   2 180
    6:      270   2 180
    7:       91   2 180