删除满足特定模式的数据帧的相邻行的集合-R

问题描述 投票:0回答:1

我在12/19发布了这个问题。我收到了一个非常有帮助的答复,但与我所寻找的不完全相同。然后这个问题被三个人以需要进一步关注的规范结束。说明表明我可以更新问题或发布新问题,但在对其进行编辑以使其更加集中之后,它仍然处于关闭状态。所以,我再次发布它。

这里是已编辑问题的链接,包括更简洁的数据集(曾是一个关键评论):Identifying a specific pattern in several adjacent rows of a single column - R

但是,如果不允许链接,则为内容:

我需要从数据中删除一组特定的行。在我们的调查(自动电话调查)中,调查工具将在呼叫期间尝试三次,以提示被调查者输入答复。问题三个超时后,调查工具挂断。当呼叫转到某人的语音信箱时,通常会发生这种情况。

我想在发生这种情况时识别该模式,以便将其从计算通话时间中删除。

我正在寻找的模式在“交互”列中看起来像这样:

enter image description here

不必介绍。它可以是调查的任何部分,它会提示响应者三次响应,但是没有提供响应,因此呼叫失败。但是,必须将其夹在“应答”(电话接听)和“超时。呼叫失败”之间。 (失败)。

我确实尝试将我从昨天的解决方案(关于游程长度编码)中学到的知识应用于我的其他索引问题,但我丝毫没有使它起作用。所以,我在这里。

这是示例数据集:

这是4位受访者,调查工具与受访者(实质上是他们的电话)之间的每一次互动。

以下是数据框的代码:This goes to a Google Drive text editor with the code

我从瑞·巴拉达斯(Rui Barradas)得到的答复是:

removeRows <- function(X, col = "Interaction", 
                       ans = "Answer", 
                       fail = c("Timeout. Call failed.", "Partial", "Enqueueing call"))
{  
  a <- grep(ans, X[[col]])
  f <- which(X[[col]] %in% fail)
  a <- a[findInterval(f, a)]

  for(i in seq_along(a)){
    X[[col]][a[i]:f[i]] <- NA_character_
  }
  Y <- X[complete.cases(X), , drop = FALSE]
  Y
}

removeRows(survey_data)

但是,此解决方案范围太广。我只需要特别删除只进行3次尝试以提示响应但没有提供响应的行。因此,提示是Intro且没有响应,因此超时,最终呼叫失败。

谢谢!

r indexing pattern-matching one-to-many
1个回答
0
投票

我通常会使用dplyr软件包。我敢肯定,如果需要,可以将该方法修改为使用base R,但dplyr具有预制的功能,可以使其更容易使用。代码中的注释以说明其功能。

df2 <- df %>%
  # Find any entry where there were three timeouts evenly spaced afterwards and set TRUE.
  # You can add other conditions here if needed (to check even leading values).
  mutate(triple_timeout = ifelse(
    lead(Interaction,n=1) == "Timeout" & 
      lead(Interaction,n=3) == "Timeout" & 
      lead(Interaction,n=5) == "Timeout",
    TRUE,
    FALSE
  )) %>%
  # Lead will have some NA values so fill those in
  mutate(triple_timeout = ifelse(is.na(triple_timeout),FALSE,triple_timeout)) %>%
  # Every triple timeout has six entries that should be true, but only the first is id'd.
  # Use an `or` logic and lag statements to set value to true for 5 entries after any TRUE
  mutate(triple_timeout = triple_timeout | 
           lag(triple_timeout,n=1) |
           lag(triple_timeout,n=2) |
           lag(triple_timeout,n=3) |
           lag(triple_timeout,n=4) |
           lag(triple_timeout,n=5)
         ) %>%
  # Lag will have some NA values to fill those in
  mutate(triple_timeout = ifelse(is.na(triple_timeout),FALSE,triple_timeout)) %>%
  # Filter out any TRUE triple_filter
  filter(!triple_timeout) %>%
  # Remove the filter column
  select(-triple_timeout)
© www.soinside.com 2019 - 2024. All rights reserved.