list={1,2,3,NaN,2}
I'd like to calculate the mean of this list, ignoring the NaN
.
Answer should be 2
if the NaN
is ignored.
Seems like this should be crazy simple, but I haven't seen anything reasonable.
Thanks in advance.
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityIf your NaN
comes from an external program and is just some symbol, then
Mean @ Select[list, # =!= NaN &]
or
list /. NaN -> Nothing // Mean
2
NaN
(that he maybe typed in). This is likely the case. But there are dangerous things that look like "NaN" in Mathematica: mathematica.stackexchange.com/q/19026/12 Even if he did type it in, he should be aware that in Mathematica, NaN
has no special meaning the same way Indeterminate
does.
$\endgroup$
Nothing
.
$\endgroup$
Well, it is a bit more nuanced in my opinion. It seems like the right functionality is to actually do keep track of the illegal entries in the system, similar to keeping missing variables for the statistical analysis in other packages. If that's the case, the more appropriate way is to actually code them with Missing
. Then the computation can be done ignoring such entries, but the list would still retain the structure of the original data and can always be used for any analysis that do care about missing observations.
list = {1, 2, 3, 0, 2, 3, 5};
listnothing = list /. {0 -> Nothing};
listmissing = list /. {0 -> Missing["Not A Number"]};
Mean[listnothing]
Mean[DeleteMissing[listmissing]]
8/3
8/3
So far so good, but compare what happens if you want to plot the lists:
Row[MapThread[
ListLinePlot[#, PlotLabel -> Style[#2, Bold, 15],
ImageSize -> Medium] &,
{{list, listnothing, listmissing},
{"Original List", "List with Nothing", "List with Missing"}}]]
Not only the shape is wrong (it show the connection between points that doesn't exist), but also the number of observations is wrong in the case of Nothing
, so the more appropriate way for the data processing is to use Missing
.
Mean@Cases[{1, 2, 3, NaN, 2}, Except[NaN]]
(* 2 *)
Mean@DeleteCases[{1, 2, 3, NaN, 2}, NaN]
(* 2 *)
Solve[Mean[{2, nan, 1, 4}] == nan]
Or
Solve[Mean[list] == nan]
NaN
in Mathematica. Where did this list come from? Did you type it in? Was it returned by a library? Please edit your question and make this clear. $\endgroup$Indeterminate
. $\endgroup$Missing[]
if you're uncomfortable withIndeterminate
. $\endgroup$