问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/18469432/r-how-to-apply-moving-averages-to-subset-of-columns-in-a-data-frame