【问题标题】:Removing two specific elements and all elements between in a column of a dataframe删除数据框列中的两个特定元素和所有元素
【发布时间】:2019-10-14 20:19:01
【问题描述】:

我正在使用一个跟踪软件,它可以在 xy 坐标平面上跟踪对象。我一直在使用它来计算 y 坐标中的位置变化,但是跟踪软件留下了一些伪影。通常,跟踪器会跳到一个角落,在那里停留几帧,然后跳回来。我的数据最终会是这样的:

yposition <- c(400,402,403,404,405,407,80,81,83,80,402,401,399,397, 398, 398, 653, 653, 654, 395, 392, 391)
dataframe <- data.frame(yposition)
velocity <- c(0,2,1,1,1,2,327,1,2,2,-322, -1,-1, -2, 1, 0, -255, 0, 1, 259, -3, -1)
dataframe <- cbind(dataframe,velocity)

这种情况下的伪影是 yposition 跳到 80 并返回,以及跳到 653 并返回。有没有办法去除这些工件对应的位置变化值(在这种情况下,从 327 到 -322 的元素,以及从 -255 到 259 的元素)?

【问题讨论】:

    标签: r dataframe data-manipulation artifact


    【解决方案1】:

    这在实践中有点棘手,因为不清楚如何识别你的基础级别而不是跳跃。

    如果我们假设您的系列总是从normal 级别开始,您可以使用diffcumsum 的组合来排除信号中的跳转:

    jump.level <-  150 # this value is arbitrary
    yposition[abs(cumsum(c(0, diff(yposition)))) < jump.level]
    # [1] 400 402 403 404 405 407 402 401 399 397 398 398 395 392 391
    

    要过滤你的data.frame,你可以提取与which匹配的元素的索引:

    i <- which(abs(cumsum(c(0, diff(yposition)))) < jump.level)
    dataframe[i, ]
    
    
    

    【讨论】:

    • 感谢您的指导!
    【解决方案2】:

    如果移除是基于速度的,我们需要移除速度突变的行和后面的行,直到遇到另一个突变。:

    # threshold for velocity
    threshold <- 5
    isAbnormal <- abs(dataframe$velocity) > threshold
    indexes <- which(isAbnormal)
    

    由于我们需要删除的开始行和结束行总是成对出现,所以我们知道需要删除第 7 到 11 行和第 17 到 20 行。

    > indexes 
    [1]  7 11 17 20
    

    我们需要删除两对(7:1117:20):

    pairs <- split(indexes,rep(1:(length(indexes)/2),times = 1,each = 2))
    
    > pairs
    $`1`
    [1]  7 11
    
    $`2`
    [1] 17 20
    

    将对转换为向量,并删除这些行:

    remove_rows <- Reduce(
        function(x,y) c(x,y),
        Map(function(x) x[1]:x[2],pairs)
    )
    
    
    > remove_rows
    [1]  7  8  9 10 11 17 18 19 20
    
    > dataframe[-remove_rows,]
       yposition velocity
    1        400        0
    2        402        2
    3        403        1
    4        404        1
    5        405        1
    6        407        2
    12       401       -1
    13       399       -1
    14       397       -2
    15       398        1
    16       398        0
    21       392       -3
    22       391       -1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      相关资源
      最近更新 更多