Message Boards Message Boards

0
|
2033 Views
|
3 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Mapping AssociateTo to a list of association fails

I'm trying to update the value of a field in all records of a dataset by applying a function to the value of the field. I had no luck working with a dataset, so I converted the dataset to a list of associations and mapped AssociateTo. However, I always get the error message "is not a variable with a value, so its value cannot be changed." I checked with chapGPT with a simpler problem, and it gave me this code as an example

list = {<|"a" -> 1, "b" -> 2|>, <|"c" -> 3, "d" -> 4|>}
Map[AssociateTo[#, "e" -> 5]&, list]
(* Output: {<|"a" -> 1, "b" -> 2, "e" -> 5|>, <|"c" -> 3, "d" -> 4, "e" -> 5|>} *)

However, this code returns the same error.

list = {<|"a" -> 1, "b" -> 2|>, <|"c" -> 3, "d" -> 4|>};
Map[AssociateTo[#, "e" -> 5] &, list]
During evaluation of In[149]:= AssociateTo::rvalue: <|a->1,b->2|> is not a variable with a value, so its value cannot be changed.
During evaluation of In[149]:= AssociateTo::rvalue: <|c->3,d->4|> is not a variable with a value, so its value cannot be changed.
Out[150]= {AssociateTo[<|"a" -> 1, "b" -> 2|>, "e" -> 5], 
 AssociateTo[<|"c" -> 3, "d" -> 4|>, "e" -> 5]}

I'd appreciate any advice. Thanks

POSTED BY: George Clapp
3 Replies

Hi George,

There are two ways to do this:

ClearAll[doubleAge]
doubleAge[age_?NumericQ] := age*2

titanic = ExampleData[{"Dataset", "Titanic"}];
a = titanic[All, <|#, "age" -> doubleAge[#age]|> &]; 
b = titanic[All, {"age" -> doubleAge}]; 
a === b
(* True *)
POSTED BY: Carl Verdon

Works perfectly! Thanks!

POSTED BY: George Clapp

Hi George,

Using a Dataset

titanic = ExampleData[{"Dataset", "Titanic"}]

ClearAll@doubleAge;
doubleAge[age_?NumericQ] := age * 2;

titanic[All, <|#, "age" -> doubleAge[#age]|> &]

You can replace doubleAge with any function and replace age with any column name.

POSTED BY: Rohit Namjoshi
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract