Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the mean of compass directions which cross 360/ 0 degrees

Tags:

r

mean

directions

Given a data set of compass directions like this:

A<-c(1,1,1,2,2,2,3,3,3,4,4,4)
CompDir<-c(350,358,355,358,2,356,180,173,170,2,3,359)

DF<-data.frame(A,CompDir)

If I want to take an average by group:

aggregate(DF[,2],list(DF$A),mean)

I run into trouble when I cross the 360/ 0 threshold.

  Group.1        x
1       1 354.3333
2       2 238.6667
3       3 174.3333
4       4 121.3333

The means for groups 2 and 4 are incorrect, so how do you correctly calculate means for this kind of directional data?

like image 907
Vinterwoo Avatar asked Sep 13 '25 01:09

Vinterwoo


1 Answers

Calculate the mean of sin and cos, then use atan2 to get the direction.
As the functions are calculating in radians the given directions need to converted by first dividing and then multiplying by 180 and pi.

tt <- aggregate(cbind(x = sin(DF$CompDir/180*pi), y = cos(DF$CompDir/180*pi)), DF["A"], mean)
cbind(tt[1], CompDir = (atan2(tt$x, tt$y)/pi*180) %% 360)
#  A    CompDir
#1 1 354.333872
#2 2 358.666366
#3 3 174.331668
#4 4   1.333465
like image 182
GKi Avatar answered Sep 15 '25 17:09

GKi