Create a new dataset column based on the row key

After some fiddling, I have discovered that MapIndexed works for associations and came up with this solution:

dataset[MapIndexed[Append[#1, "Column2" -> f@#2[[1, 1]]] &]]

or, more cryptically,

dataset[MapIndexed[<|#1, "Column2" -> f@#2[[1, 1]]|> &]]

I think Andrei's response using MapIndexed is superior, but I'll offer up AssociationMap as an alternative -- partly because it is a legitimate contender and partly to illustrate a work-around for a common Dataset problem.

First, here is AssociationMap in action:

dataset[AssociationMap[#[[1]] -> <| #[[2]], "Column2" -> f[#[[1]]] |> &]]

dataset screenshot

The result is structurally correct, but unfortunately the Dataset type inferencer is presently incapable of determining the resulting type correctly (as of V11). As a consequence, it visualizes the dataset in a less than useful fashion.

We must invoke the type deducer to fix up the visual rendition. We do this by adding a terminal Dataset operator to the query:

dataset[AssociationMap[#[[1]] -> <|#[[2]], "Column2" -> f[#[[1]]]|> &] /* Dataset]

dataset screenshot

Tags:

Dataset