Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have a series of frequencies of values, e.g. 5 times 1, 10 times 2 and 5 times 3, as in

list={{1,5},{2,10},{3,5}}

and I would like to convert this to long notation as in

list2={1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3}

what is the most elegant way to do this in Mathematica?

share|improve this question
add comment

1 Answer 1

up vote 5 down vote accepted

I added timings - 3rd from the bottom is fastest. I am sure there are faster versions. If speed is important you can parallelize or come up with a Compile-ed solution.

In[1]:= list = RandomInteger[{3, 12}, {10^7, 2}];

In[2]:= list // Developer`PackedArrayQ
Out[2]= True

In[3]:= Table[#1, {#2}] & @@@ list // Flatten; // AbsoluteTiming
Out[3]= {22.015290, Null}

In[4]:= Join @@ (Table[#1, {#2}] & @@@ list); // AbsoluteTiming
Out[4]= {18.528328, Null}

In[13]:= Join @@ ConstantArray @@@ list; // AbsoluteTiming
Out[13]= {18.261945, Null}

In[5]:= ConstantArray[#1, #2] & @@@ list // Flatten; // AbsoluteTiming
Out[5]= {43.177745, Null}

In[6]:= NestList[# &, #1, #2 - 1] & @@@ list // Flatten; // AbsoluteTiming
Out[6]= {30.278883, Null}

In[7]:= Join @@MapThread[ConstantArray, Thread[list]]; // AbsoluteTiming
Out[7]= {15.465663, Null}

In[8]:= Flatten@ MapThread[ConstantArray, Thread[list]]; // AbsoluteTiming
Out[8]= {40.184748, Null}

In[9]:= Join @@ MapThread[Table[#1, {#2}] &, Thread[list]]; // AbsoluteTiming
Out[9]= {18.716637, Null}

In[3]:= Inner[ConstantArray, Sequence @@ Transpose@list, Join]; // AbsoluteTiming
Out[3]= {16.525300, Null}
share|improve this answer
    
Thx millions for the many possible solutions!! –  Tom Wenseleers Apr 12 at 10:25
    
@TomWenseleers I added some timings ;-) –  Vitaliy Kaurov Apr 12 at 10:30
    
Great - many thx! –  Tom Wenseleers Apr 12 at 10:39
    
I am getting better timings with Join @@ ConstantArray @@@ list: about 50 percent of the timings for ConstantArray[#1, #2] & @@@ list // Flatten and about as good as Join @@MapThread[ConstantArray, Thread[list]]. (+1) –  kguler Apr 12 at 11:00
    
... Similarly for Inner[ConstantArray, Sequence @@ Transpose@list, Join] :) –  kguler Apr 12 at 11:56
show 1 more comment

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.