# Populate data with ratio to previous element

I have a data which looks like this {x,y}:

data={{1,3},{2,4},{3,5},{4,6}}

I need to add another column and define it as current element divided by previous element.

This could be done like this:

For[i = 1, i <= Length[data], i++,
If[i == 1, data[[i]] = Append[data[[i]], 1],
data[[i]] = Append[data[[i]], data[[i, 2]]/data[[i - 1, 2]]]]]

However, I think that in Mathematica there may be a better way to do it

What is the easiest way to do this in Mathematica?

• Is there any rule about the first element in a new column or is it always 1?
– Kuba
May 16, 2017 at 11:11
• it's always 1, since there is no previous element May 16, 2017 at 11:19

Join[
data
, List /@ Prepend[Ratios @ data[[;; , 2]], 1]
, 2
]
Join[{AppendTo[data[[1]], 1]},
Table[{data[[i]][[1]], data[[i]][[2]],
data[[i]][[2]]/data[[i - 1]][[2]]}, {i, 2, Length@data}]]

{{1, 3, 1}, {2, 4, 4/3}, {3, 5, 5/4}, {4, 6, 6/5}}

Flatten[Riffle[#, Ratios@Prepend[#2 & @@@ #, Last@First[#]]], 1]&@data~Partition~3
(* {{1, 3, 1}, {2, 4, 4/3}, {3, 5, 5/4}, {4, 6, 6/5}} *)
Transpose[{#1, #2, {1}~Join~Ratios[#2]} & @@ Transpose[data]]