Group Abstract Group Abstract

Message Boards Message Boards

0
|
2.6K Views
|
2 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Using DeleteCases and Pure Functions

POSTED BY: Roger J Brown
2 Replies
Posted 3 years ago

Cases and DeleteCases use pattern expressions. Select uses predicates.

None of the elements of test1 match the pattern #[[2]] == 110461 &, so none of them get removed. In this case, the pattern is just a literal expression because there are none of the usual pattern decorations in the expression.

With your forbid list, you could do this (in theory)

Select[test1, Not[MemberQ[forbid, #[[2]]]] &]

The problem here is that your forbid list uses integers, but the data you're wanting to match against are finite precision reals. You could fix this with (notice the decimal points)

forbid = {110468., 110512.}

But I don't know where your data in test1 is coming from. There could be issues with equality checks on reals that "should" be equal but whose representations in fact are not. So this approach may need to be extended further.

POSTED BY: Eric Rimbey

There are a couple of errors along the way.

test1 = {{"A", 110468., 1978., 0.142501846}, {"A", 110512., 1978., 
    0.171648613}, {"A", 110540., 1978., 0.121514693}, {"A", 111721., 
    1978., 0.218872092}, {"A", 111722., 1978., 0.083322812}, {"A", 
    111725., 1978., 0.120864387}, {"A", 111728., 1978., 
    0.139541269}, {"A", 111916., 1978., 0.285463369}, {"A", 110468., 
    1979., 0.542969073}, {"A", 110512., 1979., 0.192196573}};

First is that Cases is pattern-match based, in contrast to the functional criterion Select. So you can do like so.

DeleteCases[test1, aa_ /; aa[[2]] == 110468]

(* Out[5]= {{"A", 110512., 1978., 0.171649}, {"A", 110540., 1978., 
  0.121515}, {"A", 111721., 1978., 0.218872}, {"A", 111722., 1978., 
  0.0833228}, {"A", 111725., 1978., 0.120864}, {"A", 111728., 1978., 
  0.139541}, {"A", 111916., 1978., 0.285463}, {"A", 110512., 1979., 
  0.192197}} *)

For the multiple criteria use of Select, you want And rather than Or to get the correct logic.

Select[test1, #[[2]] != 110468 && #[[2]] != 110512 &]

(* Out[8]= {{"A", 110540., 1978., 0.121515}, {"A", 111721., 1978., 
  0.218872}, {"A", 111722., 1978., 0.0833228}, {"A", 111725., 1978., 
  0.120864}, {"A", 111728., 1978., 0.139541}, {"A", 111916., 1978., 
  0.285463}} *)

Also there is the Wolfram Function Repository resource function Discard that can be used.

ResourceFunction["Discard"][test1, #[[2]] == 110468 &]

(* Out[11]= {{"A", 110512., 1978., 0.171649}, {"A", 110540., 1978., 
  0.121515}, {"A", 111721., 1978., 0.218872}, {"A", 111722., 1978., 
  0.0833228}, {"A", 111725., 1978., 0.120864}, {"A", 111728., 1978., 
  0.139541}, {"A", 111916., 1978., 0.285463}, {"A", 110512., 1979., 
  0.192197}} *)
POSTED BY: Daniel Lichtblau
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard