I have data in the following form. I have a list of values and a list of frequencies that indicate how often each value has occurred.
Example list of values: {5,7,4}
Example list of frequencies: {1,2,3}
I would like to obtain the original data from which such a histogram was generated. Any suggestions on how to do this with Mathematica ?
Example: {5,7,7,4,4,4}
Answer
Without looking at performance, but only on understanding: First, you create a function f
which takes a value
and a count
and which reproduces the value
exactly count
times. In the simplest case
f[val_, count_] := ConstantArray[val, count]
and you can call f[3,4]
to get {3,3,3,3}
. Now, you combine your input arrays so that you can call f
directly for each pair. For this, you can use MapThread
. To create you final result, you have to Flatten
the output:
Flatten[MapThread[f, {{5, 7, 4}, {1, 2, 3}}]]
This all can of course be combined into one call
vals = {5, 7, 4};
counts = {1, 2, 3};
Flatten[MapThread[ConstantArray, {vals, counts}]]
or
ConstantArray @@@ Transpose[{vals, counts}] // Flatten
or (to simplify kgulers approach)
Inner[ConstantArray, vals, counts, Join]
and many more
Comments
Post a Comment