获得后续行之间的角度差异

时间:2017-12-15 08:50:39

标签: r 360-degrees

我正在努力设计一个有效的解决方案,该解决方案可以在14*10e6 records上运行,并且可以将element_iddifference)的每个-分配给它之前的{{1} }}。显然,对于每个element_id,delta总是等于element_id == 1,因为它没有先前要比较的元素。

考虑如下的data.frame:

NA

这个问题与其他与连续行之间的差异有关的问题是,set.seed(1234) ID <- c(rep(1, 6), rep(2, 5)) element_id <- c(seq.int(1, 6), seq.int(1, 5)) degree <- as.integer(runif(11, 0, 360)) #angular degrees goes from 0 to 359 because 0 is also 360. mydf <- data.frame(ID, element_id, degree) element_id等于i350 element_id等于i+1,差异应为10

1 个答案:

答案 0 :(得分:2)

您可以尝试功能getDifference()。功能getDifference()

  1. 获得两度之间的差异
  2. 180添加到该差异
  3. 获取360%% 360)的模数并减去180
  4. 代码:

    # Function to calculate difference in degrees
    getDifference <- function(degreeA = 0, degreeB = 0) {
        (degreeA - degreeB + 180) %% 360 - 180
    }
    # Test function
    getDifference(10, 350)
    # [1] 20
    getDifference(350, 10)
    # [1] -20
    

    申请OPs数据

    # 1. Get difference with previous row (data.table shift)
    # 2. For each ID is done using data.table by 
    library(data.table)
    setDT(mydf)
    mydf[, degreeDiff := getDifference(degree, shift(degree)), ID]
    
    #    ID element_id degree degreeDiff
    # 1:  1          1     40         NA
    # 2:  1          2    224       -176
    # 3:  1          3    219         -5
    # 4:  1          4    224          5
    # 5:  1          5    309         85
    # 6:  1          6    230        -79
    # 7:  2          1      3         NA
    # 8:  2          2     83         80
    # 9:  2          3    239        156
    #10:  2          4    185        -54
    #11:  2          5    249         64