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.

Is there an equivalent command of WeightedData (new in version 9) in Mathematica 8 or I have to define it by myself? I haven't found anything in the site or googleing it... If there is not such command do you have some suggestions for defining it?

share|improve this question
    
In order to create your own WeightedData you need to define it separately for every function that is supposed to accept it, I think. E.g. Unprotect[Mean]; Mean[WeightedData[data_,weight_]]:= data.weight/Total[w];. You should now be to do this: obj = WeightedData[data,weights]; Mean[obj]. –  Pickett Dec 18 '13 at 12:30

1 Answer 1

up vote 5 down vote accepted

It might be useful to consider TagSet here, to provide a new rule to Mean when it encounters your new data object:

weightedData/:Mean[data_weightedData] :=Mean[List@@data[[1]]]

You can style your object so it looks the same as the M9 object:

Format[weightedData[data_]]:=Panel["weightedData[" <> ToString[Length[data]] <> "]"];

Now a function that builds your data object, there should be more error checking than currently implemented and MapThread was the first thing I thought of:

weightedData[data_, weights_] /; Length[data] == Length[weights]:= Module[{weighted},
weighted = MapThread[#1/#2 &,
{data1,weights}];
weightedData[weighted]]

Make some data and test it:

In[10]:=data1={1,2,3};
weights={4,5,6};
test1=weightedData[data1,weights];
Mean[test1]
Out[10]:=23/60

To make other functions play nice just use TagSet again

weightedData /: ListLinePlot[data_weightedData]:=ListLinePlot[List @@ data[[1]]];
ListLinePlot[test1]

enter image description here

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.