5
$\begingroup$

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?

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

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}
$\endgroup$
  • $\begingroup$ Thanks, Young. Can the weighting factor be negative? $\endgroup$ – dudulu Jun 20 '16 at 2:28
  • $\begingroup$ No. I didn't know that was a requirement $\endgroup$ – Young Jun 20 '16 at 2:30
  • $\begingroup$ The data can be negative. The weights and data can be fractions. $\endgroup$ – Young Jun 20 '16 at 2:36
  • $\begingroup$ @dudulu, exactly what application is having you consider negative weights? $\endgroup$ – J. M. will be back soon Jun 20 '16 at 5:06
  • $\begingroup$ @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. $\endgroup$ – Valerio Jun 3 '17 at 17:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.