Excel:连续3次或多次出现字符串中的值

时间:2018-08-06 10:32:52

标签: excel

需要计算连续3次或更多次连续发生0的实例的计数。

CAR_NO  1   0   0   0   1   1   0   0   1   0   1   0   0   0   0   1   1

在上述情况下,单元格A1为CAR_NO,而B1:R1为0或1。我需要计数出现0次3次或以上的实例的数量。

最终输出为2。ASB1:D1有3次发生0,而M1:P1有4次发生0。

4 个答案:

答案 0 :(得分:2)

使用Base R:
rle函数可计算向量中等值游程的长度和值。

x <- c(1 ,0 ,0 ,0 ,1 ,1 ,0 ,0 ,1 ,0 ,1 ,0 ,0 ,0 ,0 ,1 ,1)
rlx <- rle(x)

rlx
Run Length Encoding
    lengths: int [1:9] 1 3 2 2 1 1 1 4 2
    values : num [1:9] 1 0 1 0 1 0 1 0 1

sum(rlx$lengths[x==0] >=3, na.rm = TRUE)
[1] 2


PS:@先生。作为OP“原始帖子”发布的不合格选民答案包括R标签。

答案 1 :(得分:1)

Excel vba udf

参数:

arg1 rng 范围,例如A1:R1。必须为1行宽。

arg2 conecutiveRun 。所需的连续实例数。默认值3。

arg3 searchValue 。要匹配以连续运行的值。默认值为0。

Public Function GetCount(ByVal rng As Range, Optional consecutiveRun As Long = 3, Optional searchValue As Variant = 0) As Variant
    Dim arr(), i As Long: arr = rng.Value
    If UBound(arr, 2) < consecutiveRun Or rng.Rows.Count > 1 Then
        GetCount = CVErr(xlErrNA)
    End If
    For i = LBound(arr, 2) To UBound(arr, 2) - consecutiveRun
        If Not (IsEmpty(arr(1, i))) And arr(1, i) = searchValue _
           And Not (IsEmpty(arr(1, i + 1))) And arr(1, i + 1) = searchValue _
           And Not (IsEmpty(arr(1, i + 2))) And arr(1, i + 2) = searchValue Then
            GetCount = GetCount + 1
        End If
    Next i
End Function

数据:

Data

答案 2 :(得分:0)

使用VBA

Function getCount(byVal Rng as Range) As Long
    Dim str As variant

    str = Application.Transpose(Application.Transpose(Rng.Value))
    if isarray(str) then str = Join(str, "")
    With CreateObject("vbscript.regexp")
      .Global = True
      .ignorecase = True
      .MultiLine = True
      .Pattern = "0{3,}"
      getCount = .Execute(str).Count
    End With
End Function

答案 3 :(得分:0)

好吧,看到有一个MySQL标记(也许这是代码高尔夫的标记)...

implementation 'com.github.johnkil.android-robototextview:robototextview:4.0.0'

...哦,或者只是...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table 
(id SERIAL PRIMARY KEY
,CAR_NO INT NOT NULL
);

INSERT INTO my_table (car_no) VALUES
(1),(0),(0),(0),(1),(1),(0),(0),(1),(0),(1),(0),(0),(0),(0),(1),(1);

SELECT COUNT(*) 
  FROM 
     ( SELECT id
            , car_no
            , CASE WHEN @prev = car_no THEN @i:=@i+1 ELSE @i:=1 END i
            , @prev:= car_no 
         FROM my_table
            , (SELECT @prev:=null,@i:=0) vars 
        ORDER 
           BY id
     ) x 
 WHERE i = 3;
+----------+
| COUNT(*) |
+----------+
|        2 |
+----------+
1 row in set (0.01 sec)