简体   繁体   中英

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

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 (ie 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.

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

请注意,这会将data.frame转换为矩阵-如果您需要将输出作为data.frame, data.frame(...)其包装在data.frame(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM