How can you replace a column of a Dataset with another column or list?

Consider the dataset below with a "x" and a "CH 1" column: How can I replace the "x" column with a new set of data? For example, how could I replace "x" with values starting from 0 and incrementing in steps of 0.033?

The easiest way to do this, is probably by using Part assignment. Unfortunately, though, that doesn't work on Datasets, so we have to convert back to Normal form to do so. Here's an example:

Create example dataset:

length = 10;
dat = Dataset[
AssociationThread[{"x", "y"}, #] & /@ RandomInteger[{1, 100}, {length, 2}]
]


Create values to replace the x column:

newcolumnX = Range[length]


Use Part assignment to replace the column values; then convert back to Dataset:

dat = Normal[dat];
dat[[All, "x"]] = newcolumnX;
dat = Dataset[dat]


Alternatively, you can Transpose the dataset and then Append/Prepend a new column in one go (and then transpose back):

dat = Transpose[
Prepend[Transpose[dat], "x" -> newcolumnX]
]

• Excellent, thanks so much. It's definitely convoluted which is a pity, but this also solves my ListLinePlot problem. It's not possible to use ListLinePlot[{dataset1, dataset2}], but it is possible to use ListLinePlot[{Normal[dataset1], Normal[dataset2]}]. Thanks! – Moppentapper Sep 12 '18 at 11:04

You can create a new Dataset as a copy of the old one with one column replaced. For completeness, here is some code that generates a test dataset similar to yours:

ds = Dataset[
Inner[
<|"x" -> #1, "ch1" -> #2|> &,
Range[2.5, 3.2, 0.1],
RandomReal[{-1., 1.}, 8],
List
]
]


Now we wish to replace the "x" column with the new entries

newx = Subdivide[0, 0.033, 8]


We can do this in a single line:

ds = ds[MapIndexed[<|#1, "x" -> newx[[#2[]]]|> &]]


The idea is to apply a function (MapIndexed) on the top level (first parameter of ds), such that we can access the entire table. Here, #1 is the entire row and #2 is the row-number wraped in {}. We use the fact that "If there are multiple elements with the same key [in an Association], all but the last of these elements are dropped", according to the help details. Tested in Mathematica 11.3.0.