# How to apply BinCounts to weighted data

For example, I have an array:

data = {1, 2, 3, 4, 5, 6, 7, 8, 9}


and a corresponding list of weighting factors

weight = {5, 4, 5, 2, 4, 2, 1, 1, 1}


Evaluating

BinCounts[data, {1, 9, 1}]


gives

{1, 1, 1, 1, 1, 1, 1, 1, 1},

but

{5, 4, 5, 2, 4, 2, 1, 1, 1}

is the result wanted. How can I get this?

• Presumably you've already tried to use WeightedData[]? – J. M. will be back soon Jun 19 '16 at 21:11
• BinCounts[ Catenate@MapThread[ConstantArray, {data, weight}], {1, 9, 1}] – ciao Jun 19 '16 at 21:14
• With WeightedData you must use Histogram or HistogramList. If the data points are all integers, use Merge[Total]@Thread[data -> weight]. – Szabolcs Jun 19 '16 at 21:15
• @ciao your solution works only with integer data and weights; could you please generalize it to non-integer data and weights? – Valerio Jun 3 '17 at 17:24

To formalize the comments, here is the complete code:

data = {1, 2, 3, 4, 5, 6, 7, 8, 9};
weight = {5, 4, 5, 2, 4, 2, 1, 1, 1};

Last[HistogramList[WeightedData[data, weight], 9]]


Which outputs

{5, 4, 5, 2, 4, 2, 1, 1, 1}

• Thanks, Young. Can the weighting factor be negative? – dudulu Jun 20 '16 at 2:28
• No. I didn't know that was a requirement – Young Jun 20 '16 at 2:30
• The data can be negative. The weights and data can be fractions. – Young Jun 20 '16 at 2:36
• @dudulu, exactly what application is having you consider negative weights? – J. M. will be back soon Jun 20 '16 at 5:06
• @Young your solution works well. However, it is quite slower than BinCounts. Could you please think of other solutions which may be faster? I need to apply this function to very large datasets. – Valerio Jun 3 '17 at 17:26