Tell me more ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have data in form

list of values ex. {5,7,4} list of frequecies ex. {1,2,3}

I would like to obtain the original data from which such a histogram was generated

ex. {5,7,7,4,4,4}

share|improve this question

2 Answers

up vote 9 down vote accepted

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

share|improve this answer
 values = RandomSample[Range[100], 5]
 (*{72,75,44,25,60}*)
 counts = RandomInteger[{1, 5}, 5]
 (* {4,3,1,1,1} *)

Inner and Table:

 Inner[Table[#1, {#2}] &, values, counts, Join] (*thanks: Halirutan *)

Inner and ConstantArray:

 Flatten@Inner[ConstantArray, values, counts, List]

both give

 {72, 72, 72, 72, 75, 75, 75, 44, 25, 60}

Update: further variations using Thread, MapIndexed ...

 Table @@@ Thread[{values, List /@ counts}] // Flatten
 #1[[Join @@ MapIndexed[Table[First[#2], {#}] &, #2]]] &[values, counts]
 Module[{f}, Thread[f[values, List /@ counts]] /. f -> Table // Flatten]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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