9
$\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$
9
$\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} *)
| improve this answer | |
$\endgroup$
  • 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 at 13:17
  • 1
    $\begingroup$ @C.E. Thanks, I made it even shorter. $\endgroup$ – flinty Jul 6 at 13:19
10
$\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} *)
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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