R: How to apply moving averages to subset of columns in a data frame?

一曲冷凌霜 提交于 2019-12-22 00:44:19

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!