Hi if you could give some simple sample of your data that would be very helpful.
However I can initially see some problems with the use of atan().
atan takes a single argument and returns an angle in radians NOT degrees.
atan result is ambiguous because you dont know what quadrant the values are in. For instance there is not way of distinguishing whether a negative x value is because we are in the 2nd or 4th quadrant.
To solve this you can use atan2() which takes two arguments and thus removes the ambiguity see here. For intance:
using just atan you can see this problem (I am converting to degrees here)
atan(1/1) * 180/pi # first quadrant
# 45
atan(1/-1) * 180/pi # second quadrant
# -45
atan(-1/-1) * 180/pi # third quadrant
# 45
atan(-1/1) * 180/pi # fourth quadrant
# -45
As you can see you are only getting results on [-90,90] ( [-pi/2, pi/2] ).
But using atan2()
atan2(y = 1, x = 1) * 180/pi # first quadrant
# 45
atan2(y = 1, x = -1) * 180/pi # second quadrant
# 135
atan2(y = -1, x = -1) * 180/pi # third quadrant
# -135 same as 225 (360-135)
atan2(y = -1, x = 1) * 180/pi # fourth quadrant
# -45 same as 315 (360-45)
As you can see now you are able to remove the ambiguity surrounding which quadrant your values falls in using atan2.