I have the following data:

data = {{0.73, 0.75}, {0.70, 0.67}, {0.76}, {0.84}};

where the elements of data (data[[i]]) vary in length. I need to make statistics over data[[i]]. Eg I want to have the Mean and the Standard Deviation per element. How to do this with a simple rule?

  • 5
    $\begingroup$ Mean /@ data? Table[Mean[elem], {elem, data}]? $\endgroup$ – Szabolcs Dec 12 '19 at 13:03
  • 1
    $\begingroup$ over rows or collumns? For instance, the StandardDeviation of data[[3]] is nonsens, one number has no SD. $\endgroup$ – Slepecky Mamut Dec 12 '19 at 13:13
  • $\begingroup$ indeed. how to program that when there is no StandardDeviation, I get a 0? $\endgroup$ – Luigi Dec 12 '19 at 14:41

You could define a helper function that returns mean and standard deviation, but if there is only one element in the list, it returns 0 for the SD, then map it on your data:

f = (Through[{Mean, (If[Length[#] == 1, 0, StandardDeviation[#]] &)}[#]] &);
f /@ data

(* Out: {{0.74, 0.0141421}, {0.685, 0.0212132}, {0.76, 0}, {0.84, 0}} *)

Map applies f to each element on the first level in expr.

I suggest you define a new function describeData, which performs the 'statistics' you need. Then you simply do:

Map[describeData, data]

For example:

describeData = Function[{data},{Mean[data], StandardDeviation[data]}]
Grid[Map[describeData, data]]

You will be able to easily extend this function, in case you need additional information about the data (e.g. Histogram[] or Min[] and Max[]).

  • $\begingroup$ this works. How to avoid errors with StandardDeviation when data[[i]] is just one element? $\endgroup$ – Luigi Dec 12 '19 at 15:08
  • $\begingroup$ Yes, for example, you could add an If[] statement. See MarcoB's answer. $\endgroup$ – LBogaardt Dec 12 '19 at 15:20

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