Search code examples
google-sheetsarray-formulas

How to use arrayformula in Google Sheets to calculate the number of days between non adjacent data readings


Approximately once a week, I am taking data counts from a number of units. The counts are recorded along with the date and unit # and and reset to zero. In order to determine the count/day during the intervening period I need to determine the date of the previous reading for that particular unit:

​Date Unit # Data Other Data Date of previous reading
9/21/23 1 0
9/21/23 2 0
9/21/23 3 0
9/22/23 1 Other data
9/27/23 3 Other data
9/28/23 1 114 9/21/23
9/28/23 3 157 9/21/23
10/1/23 ALL Other data
10/4/23 1 Other data
10/4/23 3 Other data
10/5/23 2 110 9/21/23
10/5/23 3 112 9/28/23
10/6/23 ALL Other data
10/12/23 1 130 9/28/23
10/12/23 2 62 10/5/23
10/12/23 3 139 10/5/23

BTW. The dates are always increasing and the data are interspersed with readings that can be ignored (and are thus, presumably, irrelevant to the question but shown for context).

I am able to find the "previous dates" using INDEX, FILTER, and COUNTIFS: INDEX(FILTER(B$2:B2,D$2:D2<>"", C$2:C2=C2),COUNTIFS(C$2:C2,"="&C2,D$2:D2,"<>"&"")-1,1) but I need to copy this formula to each row and would prefer to use ARRAYFORMULA but neither INDEX nor COUNTIFS work with ARRAYFORMULA.


Solution

  • For your example, I managed to obtain the expected results with this formula :

    =map(A2:A17,B2:B17,D2:D17,
     lambda(date,unit,otherData, 
      iferror(
       let(filtered_data,
        filter(
         indirect("$A$2:$A$"&row(date)),
         indirect("$C$2:$C$"&row(date))<>"",
         indirect("$B$2:$B$"&row(date))=unit,
         indirect("$A$2:$A$"&row(date))<>date
        ),
        if(otherData="",
         index(filtered_data,
         counta(filtered_data)),""
        )
       )
      ,"")
     )
    )
    

    Obviously, you can extend the inputs in the map formula to fit your need.

    I would like to point out that this formula works with increasing dates only.

    Let me know if something is not working properly or if you need more details :)

    Antoine