Search code examples
rrotationmotion-detection

Smoothing directional (angular) data in R


I'm trying to deal with some motion analysis software tracking errors after the data is exported. For some frames the direction is rotated by 180 degrees from the "true" direction.

I would like to smooth the data set so that when the direction changes by ~180 in a single frame, it is transformed to reflect the actual angle.

Is anyone aware of a way to solve this using any of the circular statistics packages in R language such as CircStats? Alternatively, I could imagine a script that checks if frame to frame variation is near 180 degrees, subtracts 180 if this is true, then moves to the next frame. Does this sound like a reasonable approach and would it be easily implemented in R?

I'm afraid I don't have the rep to upload a figure describing the problem (it's very easy to see), but here is a example dataset.

Thanks for the help. I've been a longtime user of stack overflow but have never failed to find my answer before needing to ask before.

David

edit - attached image enter image description here


Solution

  • It was an interesting problem to solve! It needs to be iterative since whenever a value is changed, it can solve a problem but create another... Let me know if it does the trick.

    threshold <- 90
    correction <- 180
    
    dat <- read.table("angle_data.txt", header=TRUE)
    dat <- ts(dat)
    
    repeat {
        diffs <- dat - lag(dat, k = 1)
        probl <- which(abs(diffs[,2]) > threshold)
    
        if(length(probl)==0)
            break
    
        obs.1 <- dat[probl[1], 2]
        obs.2 <- dat[probl[1] + 1, 2]
    
        dat[probl[1] + 1, 2] <- obs.2 + sign(obs.1 - obs.2) * 180
    }
    

    enter image description here