3
$\begingroup$

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?

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

4 Answers 4

4
$\begingroup$
Join[
    data
  , List /@ Prepend[Ratios @ data[[;; , 2]], 1]
  , 2
]
$\endgroup$
2
$\begingroup$
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}}

$\endgroup$
2
$\begingroup$
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}} *)
$\endgroup$
2
$\begingroup$
Transpose[{#1, #2, {1}~Join~Ratios[#2]} & @@ Transpose[data]]
$\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.