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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With