Suppose that I have two lists, list1
and list2
, of ordered pairs $(x, y)$. The two lists are differently spaced in $x$; some ordered pairs in list1
and list2
have the same $x$ value, but some do not.
I would like to combine the two lists such that all ordered pairs are included in the resulting list, which I will call list
. If two ordered pairs happen to have the same $x$ value, then their $y$ values are added. Otherwise, the ordered pairs are included as-is.
Here is an example. list1
and list2
are defined as follows:
list1 = {{0, 0}, {1, 1}, {2, 4}, {3, 9}, {4, 16}};
list2 = {{0, 0.5}, {0.4, 1}, {1, 2}, {1.5, 3}, {3.25, 8}, {4, 8}};
I would like to write a function addLists
that takes list1
and list2
and returns the following list:
list = {{0, 0.5}, {0.4, 1}, {1, 3}, {1.5, 3}, {2, 4}, {3, 9}, {3.25, 8}, {4, 24}}
One way to write addLists
is to use a rather long, complicated combination of SortBy
, GatherBy
, Map
, Total
, and Transpose
:
addLists[list1_List, list2_List] := Module[{xList, yList, list},
list = SortBy[Join[list1, list2], First];
xList = DeleteDuplicates[list[[All, 1]]];
list = GatherBy[list, First];
yList = Map[Total[#[[All, 2]]] &, list];
list = Transpose[{xList, yList}]
]
addLists[list1, list2]
which gives the desired output (matching list
):
{{0, 0.5}, {0.4, 1}, {1, 3}, {1.5, 3}, {2, 4}, {3, 9}, {3.25, 8}, {4, 24}}
But, I think that there must be a simpler -- perhaps even built-in -- way to do this. Do you have any suggestions?
Union
orIntersection
. Since my desired result is essentially adding two histograms, I thought maybe there would be something built-in likeHistogramList
to do the job. $\endgroup$