R:如何将移动平均值应用于数据帧中的列子集? [英] R: How to apply moving averages to subset of columns in a data frame?

查看:162
本文介绍了R:如何将移动平均值应用于数据帧中的列子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框(training.set),其中包含83个变量的150个观察值。我想用一些移动平均线来转换这些列中的82个。问题是结果最终只有150个数值(即1列)。



如何在数据中单独应用移动平均函数,并保持第83列不变?我觉得这是超级简单,但我找不到解决方案。



我目前的代码

 #应用移动平均值在training.set数据到83行中的82行
库(TTR)#load用于SMA功能的#load TTR库
ts.sma< - SMA(training.set [,1:82],n = 10)
ts.sma

感谢您的帮助

解决方案

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

请注意,这将将您的data.frame转换为矩阵 - 将其包装在 data.frame(... )如果您需要输出为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 (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.

解决方案

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.

这篇关于R:如何将移动平均值应用于数据帧中的列子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆