Home > Software engineering >  Is there a way to count when a variable appears with (and without) another in excel?
Is there a way to count when a variable appears with (and without) another in excel?

Time:10-26

I am trying to count in Excel how many times "A" appears with (and then without) "C" horizontally when they are not in the same location every time. Does anyone know an Excel formula that would work? Here is an example of my data.

1 2 3 4 5
A B C D E
A B C D F
E G F H L
E B C H F
A I J K H

Thanks!

CodePudding user response:

To get the number of rows that have both A and C, assuming that each can only be in the row one time each:

=SUM(--(MMULT((A1:E5="A") (A1:E5="C"),TRANSPOSE(COLUMN(A1:E5)^0))>1))

This may need to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode on older versions.

To get the total without we add COUNTIF(A1:E5,"A") and sutract the formula above:

=COUNTIF(A1:E5,"A")-SUM(--(MMULT((A1:E5="A") (A1:E5="C"),TRANSPOSE(COLUMN(A1:E5)^0))>1))

Same caveat about Ctrl-Shift-Enter.

enter image description here


If the values can be present multiple times per row then we need to do:

=SUM(--((MMULT(--(A1:E5="A"),TRANSPOSE(COLUMN(A1:E5)^0))>0) (MMULT(--(A1:E5="C"),TRANSPOSE(COLUMN(A1:E5)^0))>0)>1))

Again Older versions need to use Ctrl-Shift-Enter.

enter image description here

CodePudding user response:

Admittedly, chances are you won't have access yet to the following functions. But this could be a nice usecase for enter image description here

Formula in I1 to count rows with 'A' and 'C':

=SUM(BYROW(A1:E5,LAMBDA(x,--(COUNTIF(x,"A")*COUNTIF(x,"C")))))

Or:

=SUM(--BYROW(A1:E5,LAMBDA(x,SUM(--(UNIQUE(x)={"A","C"}))=2)))

Formula in I2 to count rows with 'A' but without 'C':

=SUM(BYROW(A1:E5,LAMBDA(x,COUNTIF(x,"A")*(COUNTIF(x,"C")=0))))
  • Related