2
$\begingroup$

I have a list of about 700 smaller lists, most with different dimensions. They range from 1 element to 18 elements long.

Think like:

lst = {{1,2}, {3,4,5}, {6}, {7,8,9,10}, ...}

I simply want to take the standard deviation of each inner list, but for the life of me cannot figure out how. Ideally, my final list should be one dimensional. I have tried several workarounds, but they all come back to the problem of it being non-rectangular. I feel like it should be simple, and would love any ideas because I am stuck.

$\endgroup$
1
  • 1
    $\begingroup$ Welcome to Mathematica StackExchange! Take a look at Map. You can use it like Map[StandardDeviation, lst] or with a shorthand notation StandardDeviation /@ lst. However, note that StandardDeviation calculates the sample std. dev., which cannot be calculated for one element. You can also calculate population std. dev. with ResourceFunction["PopulationStandardDeviation"] /@ lst. $\endgroup$
    – Domen
    Jan 23, 2023 at 17:46

1 Answer 1

1
$\begingroup$
In[9]:= lst = {{1, 2}, {3, 4, 5}, {6, 7, 8, 9}, {10}};

In[11]:= Map[StandardDeviation, lst] // N

During evaluation of In[11]:= StandardDeviation::shlen: The argument {10} should have at least two elements.

During evaluation of In[11]:= StandardDeviation::shlen: The argument {10.} should have at least two elements.

Out[11]= {0.707107, 1., 1.29099, StandardDeviation[{10.}]}

The standard deviation is meaningless for single element lists. Not sure of the use case, but those lists should be dropped from your input list.

$\endgroup$
4
  • 1
    $\begingroup$ Or maybe Map[If[Length@#<2, 0, StandardDeviation@#]&, lst] $\endgroup$
    – polfosol
    Jan 23, 2023 at 18:05
  • $\begingroup$ Thank you so much! I thought the standard deviation of a single number is 0, so why does Mathematica have trouble with it? $\endgroup$
    – Claudia
    Jan 23, 2023 at 18:13
  • 2
    $\begingroup$ @Claudia take a look at the reference which says this function is equivalent to Sqrt[Variance[...]]. Now see the definition of variance. $\endgroup$
    – polfosol
    Jan 23, 2023 at 18:37
  • $\begingroup$ Ah, okay, it's because it'll be 0/0 in the variance definition. Thanks again! $\endgroup$
    – Claudia
    Jan 24, 2023 at 15:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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