6
$\begingroup$

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}.

$\endgroup$
1
  • 3
    $\begingroup$ Like Transpose[{data[[All, 1]], Differences[Prepend[data[[All, 2]], 0]]}]? $\endgroup$ Apr 22, 2020 at 16:44

5 Answers 5

6
$\begingroup$
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}} 
$\endgroup$
6
$\begingroup$

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]]];
$\endgroup$
3
$\begingroup$
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}}

$\endgroup$
3
$\begingroup$
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}}

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

Using Partition:

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

Thread@{#[[All, 1]], f@#[[All, 2]]} &@data

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}}

$\endgroup$

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.