2

I have a dataframe (training.set) that is 150 observations of 83 variables. I want to transform 82 of those columns with some moving averages. The problem is the results end up only being 150 numeric values (i.e. 1 column).

How would I apply the moving average function across each column individually in the data and keep the 83rd column unchanged? I feel like this is super simple, but I can't find a solution.

My current code

# apply moving average on training.set data to 82 of 83 rows
library(TTR)  #load TTR library for SMA functions
ts.sma <- SMA(training.set[,1:82], n = 10)
ts.sma

Thanks for your help.

A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
zlooop
  • 33
  • 1
  • 4

1 Answers1

3
apply(training.set[,1:82], 2, SMA, n=10)

Note that this will convert your data.frame to a matrix - wrap it in data.frame(...) if you need the output to be a data.frame.

Señor O
  • 17,049
  • 2
  • 45
  • 47
  • Ok, that was easy. What does the 2 represent? Also, is there a way to keep the 83rd column in the data, or do you have to use the c() function after you do the apply? – zlooop Aug 27 '13 at 15:53
  • It tells `apply` to run the `SMA` column-wise (1 == row-wise). See `?apply`. – sgibb Aug 27 '13 at 15:54
  • Yes, you can `cbind()` the result of `apply` with the 83rd column. – Señor O Aug 27 '13 at 15:57