0

Perform % change between Close and 10ema Column. Desired output is % difference close column [3]

I have my data within a dataframe

   Close            10ema   % Difference Close – 10ema / 10ema *100
12.81398            NA             NA
13.2636             NA             NA
13.54461            NA             NA
13.76941            NA             NA
13.82561            NA             NA
13.88181            NA             NA
13.76941            NA             NA
13.88181            NA             NA
13.4884             NA             NA
13.4884         13.572704   -0.621128995
13.376          13.53693964 -1.188892325
13.376          13.50767788 -0.974837314
13.4884         13.50417281 -0.11679956
13.4322         13.49108685 -0.436487059
13.376          13.47016197 -0.699041087
13.376          13.45304161 -0.572670563
13.376          13.43903404 -0.469037013

I am looking to perform the % difference between Close and 10ema.

In Excel I would use:

=Sum (close 1 - 10ema)10ema *100

The R code I am using:

new.dataframe$close.prct.ema.10 <- apply(new.dataframe[,c('Close', 'ema.10')], 1, function(x) { (x[1]-x[2]/x[2]) * 100 } )

I am specifying the columns to apply the function too in [,C ('Close', 'ema.10')]

Also the 1 before the function is telling the code to perform the function row by row as in:, 1, function (x)

This portion (x[1]/x[2]/x[2]) * 100 }) is an attempt to say: Close - ema10 / ema 10 *100

The 1 and 2 point to the order that the column names are stated in the [,C ('Close', 'ema.10')

However, the result is not working. The code looks just fine to me and makes sense, what am I missing here?

M--
  • 25,431
  • 8
  • 61
  • 93
Andrew Bannerman
  • 1,235
  • 2
  • 16
  • 36
  • 1
    Difficult to help without seeing the data: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example. – neilfws Jun 14 '17 at 00:34
  • 1
    Possible duplicate of [Specify widths and heights of plots with grid.arrange](https://stackoverflow.com/questions/36198451/specify-widths-and-heights-of-plots-with-grid-arrange) – M-- Jun 14 '17 at 02:36
  • 1
    or https://stackoverflow.com/questions/14590111/how-to-control-plot-width-in-gridextra – M-- Jun 14 '17 at 02:36
  • They use grobs and this is grob issue therefore that answer does not work for me hence my question. – Andrew Bannerman Jun 14 '17 at 02:38

1 Answers1

0

The answer is below. It was a order issue with the syntax. Here is the working solution which applies a percentage change between two columns.

new.dataframe$close.prct.ema.10 <- apply(new.dataframe[,c('Close', 'ema.10')], 1, function(x) { (x[1]-x[2])/x[2] * 100 } )

(x[1]-x[2])/x[2] * 100

Note the brackets first around (x1-x2) / 2 *100

Andrew Bannerman
  • 1,235
  • 2
  • 16
  • 36