12
$\begingroup$

I work with a complex dataset. The most simple form of this list looks like:

dat1 = {{a, b, c, {}}, {d, e, f, {1}}, {h, i, j, {2}}}

I want to select the nested {} part.

Cases[dat1, {___, {a_}} :> a, Infinity]

The result is

{1, 2}

I want to get the result:

{,1, 2}

So the result must have the first empty cell. How can I fix this?

$\endgroup$

4 Answers 4

10
$\begingroup$

Here I treat the contents of the empty element as Null and I assume either 1 element in the nested list or no element:

Cases[dat1, {x_ : Null} :> x, 2]
(* returns: {Null, 1, 2} *)
$\endgroup$
2
  • 3
    $\begingroup$ +1. I think Null is the way to go. But how about simply Cases[dat1, {___, {a_ : Null}} :> a, Infinity]? $\endgroup$
    – C. E.
    Jul 6, 2020 at 13:17
  • 1
    $\begingroup$ @C.E. Thanks, I made it even shorter. $\endgroup$
    – flinty
    Jul 6, 2020 at 13:19
11
$\begingroup$

For this use case, I would encourage you to use Map and Replace rather than Cases, since you can use multiple rules for the extraction:

Map[Replace[{{___, {}} :> Null, {___, {x_}} :> x}],
 dat1]
(* {Null, 1, 2} *)

As an alternative, you can use Replace with a level spec:

Replace[dat1, {{___, {}} :> Null, {___, {x_}} :> x}, 1]
(* {Null, 1, 2} *)
$\endgroup$
1
$\begingroup$
list = {{a, b, c, {}}, {d, e, f, {1}}, {h, i, j, {2}}};

Using Query

Query[All, -1, 1] @ list

{Missing["PartAbsent", 1], 1, 2}

% /. _Missing :> Null

{Null, 1, 2}

As one-liner

Query[# /. _Missing :> Null &, -1, 1] @ list

{Null, 1, 2}

$\endgroup$
1
$\begingroup$
dat1 = {{a, b, c, {}}, {d, e, f, {1}}, {h, i, j, {2}}};

Using ReplaceAll and Map:

dat1 /. x_List /; Length@x == 0 :> {Null} // Map[First@*Last, #] &

(*{Null, 1, 2}*)
$\endgroup$

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.