4

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

Jeppe Olsen
  • 968
  • 8
  • 19
  • 1
    How did you come up with 320 & 260?? – Sotos Nov 05 '18 at 09:17
  • In grp 1, the longest distance is from 20 to 340 = 320°. In grp 2 the longest is from 200 to 100 = 260°. Its like on a compass. – Jeppe Olsen Nov 05 '18 at 09:19
  • in a group, is it sufficient to take the difference between max and min value of the headings or do you consider clockwise differences between two consecutive headings only? – Tomas Nov 05 '18 at 09:28
  • I tried editing. I find it a bit difficult to explain, hope that its a bit clearer now. – Jeppe Olsen Nov 05 '18 at 09:56
  • 3
    It's arguably bad form to repeatedly change your example after an answer is posted. You could add new examples instead dt2 <- etc. – Frank Nov 05 '18 at 10:37
  • In grp 1, (where you currently have compass headings 340, 0, 20 in your example) if you want to find the largest angle between headings why isn't that found from 0° to 20° = 340°? – krads Nov 05 '18 at 12:05
  • It might not be completely clear what I mean, but I want to find the largest FREE angle between any two headings. from 20° to 0° there is 340°, but the heading at 340° is between those. – Jeppe Olsen Nov 05 '18 at 12:12

1 Answers1

4

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
Frank
  • 66,179
  • 8
  • 96
  • 180