【问题标题】:Error when trying to parse through data and find multiple repeated values in R尝试解析数据并在 R 中查找多个重复值时出错
【发布时间】:2021-12-21 12:59:31
【问题描述】:

基本上我想查看一系列重复数字的开始位置。例如,如果我有:

data_frame <- c(1, 7, 8, 4, 3, 7, 8, 8, 9, 3)

我想找到数字连续 3 次大于 7 的位置,我希望函数返回 5。

end_test_machine <- function(distribution_input) { 
for (i in 1:length(distribution_input)){
    if (distribution_input[i] > 7) {
      if(distribution_input[i+1] < 7) {
        end_test_position <- i
        next
      }
    } # End If Statement
    else {
      next
    }
  } # End For Loop
  return(end_test_position)
}

当我使用上面的代码块时,我总是得到错误信息:

Error in if (distribution_input[i+1] > 7) { : 
missing value where TRUE/FALSE needed

如果三个连续值的条件为真,我如何将数据输入中的下一个元素与当前位置进行比较并返回该位置?

【问题讨论】:

    标签: r dataframe shiny


    【解决方案1】:

    使用rle:

    x <- c(1, 7, 8, 4, 3, 7, 8, 8, 9, 3)
    
    with(rle(x>=7), sum(lengths[seq(which(lengths>3)[1]-1)]))
    [1] 5
    

    【讨论】:

      猜你喜欢
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2012-02-19
      • 1970-01-01
      相关资源
      最近更新 更多