简体   繁体   English

R:如何将移动平均线应用于数据框中的列子集?

[英]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. 我有一个数据框(training.set),它是83个变量的150个观察值。 I want to transform 82 of those columns with some moving averages. 我想用一些移动平均值来转换这些列中的82个。 The problem is the results end up only being 150 numeric values (ie 1 column). 问题是结果最终只能是150个数字值(即1列)。

How would I apply the moving average function across each column individually in the data and keep the 83rd column unchanged? 如何将移动平均函数分别应用于数据中的每一列,并使第83列保持不变? 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(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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