7
$\begingroup$

Considering we have a list of rules:

{ First-> {a-> "aaaa", b-> "bbbb"}, Second-> {c-> "cccc", d-> "dddd", e-> Missing["NotAvailable"], f-> Missing["NotAvailable"] }}

How can I bring this to be:

{ First-> {a-> "aaaa", b-> "bbbb"}, Second-> {c-> "cccc", d-> "dddd" }}

Thanks.

$\endgroup$
1

4 Answers 4

12
$\begingroup$
list =
 {First -> {a -> "aaaa", b -> "bbbb"}, Second -> {c -> "cccc", d -> "dddd"e -> Missing["NotAvailable"], f -> Missing["NotAvailable"]}}

DeleteCases[list, Rule[_, _Missing], Infinity]

{First -> {a -> "aaaa", b -> "bbbb"}, Second -> {c -> "cccc", d -> "dddd"}}

$\endgroup$
6
$\begingroup$

you can use DeleteMissing also

l = {First -> {a -> "aaaa", b -> "bbbb"}, 
  Second -> {c -> "cccc", d -> "dddd", e -> Missing["NotAvailable"], 
    f -> Missing["NotAvailable"]}};

Normal@DeleteMissing[Association@l, Infinity]
(*{First -> {a -> "aaaa", b -> "bbbb"},Second -> {c -> "cccc", d -> "dddd"}}*)
$\endgroup$
4
$\begingroup$

Here is another alternative using UpValues:

Block[{Missing},
 Missing /: _ -> Missing["NotAvailable"] := Sequence[];
 {First -> {a -> "aaaa", b -> "bbbb"}, 
  Second -> {c -> "cccc", d -> "dddd", e -> Missing["NotAvailable"], 
    f -> Missing["NotAvailable"]}}
 ]
(*
  {First -> {a -> "aaaa", b -> "bbbb"}, Second -> {c -> "cccc", d -> "dddd"}}
*)
$\endgroup$
5
  • $\begingroup$ That looks familiar $\endgroup$
    – Mr.Wizard
    Commented Apr 8, 2015 at 16:26
  • $\begingroup$ @Mr.Wizard really? I never would have guessed. $\endgroup$
    – rcollyer
    Commented Apr 8, 2015 at 17:15
  • 1
    $\begingroup$ @Mr.Wizard Truthfully, I'm enamored with mma's homoiconicity and I think it should be demonstrated at every opportunity. $\endgroup$
    – rcollyer
    Commented Apr 8, 2015 at 17:26
  • $\begingroup$ It is nice but beware of packed arrays. $\endgroup$
    – Mr.Wizard
    Commented Apr 8, 2015 at 17:32
  • $\begingroup$ @Mr.Wizard packed arrays can be special, along with most things that are AtomQ. $\endgroup$
    – rcollyer
    Commented Apr 8, 2015 at 17:34
3
$\begingroup$

Less elegant than DeleteCases, however an alternative:

exp = {First -> {a -> "aaaa", b -> "bbbb"}, 
  Second -> {c -> "cccc", d -> "dddd", e -> Missing["NotAvailable"], 
    f -> Missing["NotAvailable"]}}

 Delete[exp, Position[exp, _ -> _Missing]] 

Or

 Delete[exp, Drop[#, -1] & /@ Position[exp, _Missing]]

(*{First -> {a -> "aaaa", b -> "bbbb"}, Second -> {c -> "cccc", d -> "dddd"}}*)
$\endgroup$

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