# Creating a new list with new second element

Given data={{1, 34}, {2, 54}, {3, 66}, {4, 77}, {5, 92}}, I would like to create a new list such that

{{1, 34}, {2, 54-34}, {3, 66-54}, {4, 77-66}, {5, 92-77}}


which is {{1, 34}, {2, 20}, {3, 12}, {4, 11}, {5, 15}.

• Like Transpose[{data[[All, 1]], Differences[Prepend[data[[All, 2]], 0]]}]? Commented Apr 22, 2020 at 16:44

ClearAll[f]
f = SubsetMap[Differences @* Prepend[0], {All,2}]


Example:

data = {{1, 34}, {2, 54}, {3, 66}, {4, 77}, {5, 92}} ;

f @ data

  {{1, 34}, {2, 20}, {3, 12}, {4, 11}, {5, 15}}


The following works, I think

data = {{1, 34}, {2, 54}, {3, 66}, {4, 77}, {5, 92}};
data[[2 ;; 5, 2]] = Differences[data[[All, 2]]];


Output when data is called is

{{1, 34}, {2, 20}, {3, 12}, {4, 11}, {5, 15}}


Adjusting for specific lengths (dimensions of a submatrix to be replaced) is straightforward, e.g.

data[[2 ;; Dimensions[data][[1]], 2]] = Differences[data[[All, 2]]];

list = {{1, 34}, {2, 54}, {3, 66}, {4, 77}, {5, 92}};


Using SequenceCases

Prepend[First @ list] @
SequenceCases[list, {{_, a_}, {n_, b_}} :> {n, b - a}, Overlaps -> True]


{{1, 34}, {2, 20}, {3, 12}, {4, 11}, {5, 15}}

Join[{First@data},
Transpose[{Rest@data[[All, 1]], Differences@data[[All, 2]]}]]


or

Join[{First@data},
Partition[data, 2, 1] /. {{a_, b_}, {c_, d_}} :> {c, d - b}]


or

BlockMap[{First@Last@#, Last@Last@# - Last@First@#} &, {{0, 0}}~Join~
data, 2, 1]


{{1, 34}, {2, 20}, {3, 12}, {4, 11}, {5, 15}}

data = {{1, 34}, {2, 54}, {3, 66}, {4, 77}, {5, 92}};


Using Partition:

f = Subtract[#2, #1] & @@@ Prepend[{0, #[[1]]}]@Partition[#, 2, 1] &;



Result:

{{1, 34}, {2, 20}, {3, 12}, {4, 11}, {5, 15}}

Or using Table and If:

f = If[k == 1, #[[k]], {#[[k, 1]], #[[k, 2]] - #[[k - 1, 2]]}] &;

Table[f@#, {k, Length@#}] &@data


Result:

{{1, 34}, {2, 20}, {3, 12}, {4, 11}, {5, 15}}