Reputation: 167
I have the following data:
measurement <- c(1:30)
angle <- rnorm(30, 0, 0.4)
data.1 <- data.frame(measurement, angle)
And I want to make a function that returns a TRUE value for four different scenarios:
1. When 'angle' > 0.3
or 2. When 'angle' < -0.3
or 3. When 'angle' + the previous 'angle' > 0.3
or 4. When 'angle' + the previous 'angle' < -0.3
I tried it with a for loop, and I've tried it the following way, but I just don't know how to include the sum of the angle and the angle that is measured one time-step earlier (so what i'm doing here is wrong but how can i improve it? preferably on the computationally least strenuous way because I work with massive data-sets):
n<-data.1$angle
function1 <- function(n){
return(n>0.3 | n<(-0.3) | (n+(n-1))>(0.3) | (n+(n-1))<(-0.3))
}
Sorry for being an R novice but after strolling through the labyrinth of R documentation I saw no other way but to ask it here. Thanks for helping!
Upvotes: 1
Views: 145
Reputation: 118809
You can do it in a vectorised format instead of doing it for each angle one by one.
abs(data.1$angle) > 0.3 | abs(data.1$angle + c(0, head(data.1$angle,-1))) > 0.3
abs(data.1$angle) > 0.3 - the first and second conditions.
abs(data.1$angle + c(0, head(data.1$angle,-1))) > 0.3 - takes all angles and adds the previous angle to it using c(0, head(., -1))
. Then again check with abs
for 0.3 and -0.3
I get:
# [1] FALSE TRUE TRUE TRUE TRUE FALSE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE
# [15] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE TRUE TRUE
# [29] TRUE TRUE
Upvotes: 6