3
$\begingroup$

I am working on a basketball data set. I am trying to append a "Class" column which looks at the "Pos" column and assigns a 1 if a forward (C, PF, SF) or a 2 if a guard (PG, SG). I am able to map a function that determines what the Class should be.

posassign[pos_] := 
 Which[pos === "C", 1, pos === "PF", 1,   pos === "SF", 1, 
  pos === "PG" , 2, pos === "SG" , 2]
ClassCol = posassign /@ bball4[;; , "Pos"]
bball5 = bball4[All, Append["Class" -> # & /@ ClassCol]]

The results look like this: enter image description here

But when I try to append it only takes the "1" value: enter image description here

Any help would be appreciated.

$\endgroup$
1
  • 1
    $\begingroup$ Nothing really to do with your question, but you could define your posassign function like this: posassign["C" | "PF" | "SF"] = 1; posassign["PG" | "SG"] = 2. A bit cleaner to read. $\endgroup$
    – lericr
    Apr 29, 2022 at 14:07

1 Answer 1

3
$\begingroup$

For test data, I'm using the following:

bballData =
  Dataset[
    {
      <|"Pos" -> "C", "PTS" -> 100|>,
      <|"Pos" -> "PG", "PTS" -> 101|>,
      <|"Pos" -> "SF", "PTS" -> 102|>}]

Using your posassign function, you can generate a Dataset from bballData with this query:

bballData[All, <|"Pos" -> "Pos", "PTS" -> "PTS", "Class" -> posassign@*"Pos"|>]

This doesn't update the variable bballData itself (but if that's what you want just assign this new dataset to that variable). Hopefully you can see from this example how you could add/remove colums and apply other functions. I was inferring that you have a Dataset to work with, but if I've misunderstood which structure you want to apply your function to, then this would need to be ajusted.

$\endgroup$
1
  • 2
    $\begingroup$ (+1) You can also use bballData[All, <|#, "Class" -> posassign @ #Pos|> &] $\endgroup$
    – kglr
    Apr 30, 2022 at 12: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.