6
$\begingroup$

For example, I have the following data

filenameData = {<|"parameter" -> <|"a" -> 1.`, "b" -> 10.`|>, 
   "filename" -> 
    "a_1_b_10"|>, <|"parameter" -> <|"a" -> 2.`, "b" -> 20.`|>, 
   "filename" -> 
    "a_2_b_20"|>, <|"parameter" -> <|"a" -> 3.`, "b" -> 30.`|>, 
   "filename" -> 
    "a_3_b_30"|>, <|"parameter" -> <|"a" -> 4.`, "b" -> 40.`|>, 
   "filename" -> "a_4_b_40"|>}

What I want to do is to filter parameters under the key "parameter".

For example, an operation select all "a" greater than 1, "b" greater than 20, and gives

operation[Select[(#a>1&&#b>20)&]@filenameData
(*{<|"parameter" -> <|"a" -> 3.`, "b" -> 30.`|>, 
  "filename" -> 
   "a_3_b_30"|>, <|"parameter" -> <|"a" -> 4.`, "b" -> 40.`|>, 
  "filename" -> "a_4_b_40"|>}*)

What is more, after filtering, get key "filename" or "parameter", something like

operation[Select[(#a>1&&#b>20)&,"filename"]@filenameData
(*{"a_3_b_30","a_4_b_40"}*)
operation[Select[(#a>1&&#b>20)&,"parameter"]@filenameData
(*{<|"a" -> 3.`, "b" -> 30.`|>,<|"a" -> 4.`, "b" -> 40.`|>}*)

I know the operation function I devised here should be Query function, and I don't need the parameter interface as exactly as I wrote above. But I just can not figure out how to do this case with Query(generally it is kind of filtering inner level, and selecting outer level).

$\endgroup$
2
  • $\begingroup$ I don't get what you want. $\endgroup$ Jan 13, 2018 at 14:43
  • $\begingroup$ @HenrikSchumacher I just want a function operation which when apply on filenameData can produce results as shown in my post $\endgroup$
    – matheorem
    Jan 13, 2018 at 15:03

1 Answer 1

11
$\begingroup$

We must adjust the Select operator to account for the fact that the keys "a" and "b" are nested within the key "parameter":

filter = Select[(#["parameter", "a"] > 1 && #["parameter", "b"] > 20) &];

We can then obtain the desired results using that filter:

Query[filter] @ filenameData

(*
    { <|"parameter" -> <|"a" -> 3., "b" -> 30.|>, "filename" -> "a_3_b_30"|>
    , <|"parameter" -> <|"a" -> 4., "b" -> 40.|>, "filename" -> "a_4_b_40"|>
    }
*)

Query[filter, "filename"] @ filenameData

(* {"a_3_b_30", "a_4_b_40"} *)

Query[filter, "parameter"] @ filenameData

(* {<|"a" -> 3., "b" -> 30.|>, <|"a" -> 4., "b" -> 40.|>} *)
$\endgroup$
1
  • $\begingroup$ Thank you so much, WReach! It perfectly suits my need. It seems the key is that assoc[key1, key2,...] can traverse nested association. $\endgroup$
    – matheorem
    Jan 14, 2018 at 0:13

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.