Reputation: 471
I want to calculate a mean angle in radians (theta) from a series of angles (beta), which are stored in a dataframe called 'a':
time beta theta theta2
1 0 na na
2 2.426551575 na na
3 5.890842799 0.678069689 0.678069689
4 0.530641823 0.854950297 0.854950297
5 4.794960386 -0.449975202 5.833210105
6 1.271620156 0.104679019 0.104679019
7 5.789548201 -0.236747291 6.046438017
8 1.053579352 0.610520801 0.610520801
9 0.095112206 0.218351484 0.218351484
10 6.108843722 0.324783324 0.324783324
the betas are in radians and are generated as a random draw from the wrapped gauchy distribution. I want to calculate thetas (actually theta2, in radians). I did these by brute force, converting radians into positive and negative units with pi/-pi at 180 degrees, but was looking for a more elegant approach.
I had hoped that this would work (invoking both circular and dplyr packages):
a$theta<-mean.circular(c(a$beta,lag(a$beta),lag(a$beta,2))
But this only seems to return the last value of beta. I've tried subsetting and also within a loop (I have another field called time that is an incrementing integer)
time beta
1 0
2 2.426551575
3 5.890842799
4 0.530641823
5 4.794960386
6 1.271620156
7 5.789548201
8 1.053579352
9 0.095112206
10 6.108843722
theta<-0
bset<-c(0,0,0)
for (i in time){
bset<-ifelse(i<3,bset,df$beta[(i-2):i])
thetai<-mean.circular(bset)
theta<-c(theta,ifelse(is.na(thetai),0,thetai))
theta<-theta[2:(length(time)+1)]
df<-cbind(df,theta)
}
But this also is not working. Can anyone tell me what I am doing wrong?
Upvotes: 0
Views: 795
Reputation: 11128
I believe if I understood you correctly then you are trying to calculate moving averages of data which is circular in nature. If that is the case, You may choose raster's movingFun
function to get the moving averages. Since mean is not vectorized in nature, it will always return one value.
It would be good if you paste your desired output.
Here, I choose a value of lag as 2 and circular nature as True.
library(raster)
movingFun(x, n= 2, fun = mean, circular = TRUE)
Input data:
x <- c(0,2.426551575,
5.890842799,
0.530641823,
4.794960386,
1.271620156,
5.789548201,
1.053579352,
0.095112206,
6.108843722,
1.240271853,
5.350922943)
Output:
> movingFun(x, n= 2, fun = mean, circular = T)
[1] 2.6754615 1.2132758 4.1586972 3.2107423
[5] 2.6628011 3.0332903 3.5305842 3.4215638
[9] 0.5743458 3.1019780 3.6745578 3.2955974
Upvotes: 4