【问题标题】:Calculate rolling mean for each row in a data frame [duplicate]计算数据框中每一行的滚动平均值[重复]
【发布时间】:2018-09-06 13:59:57
【问题描述】:

对于看起来像这样的数据框:

Value  Id
 1      xxx-rrr-ttt
 78     ggg-oop-rty
 97     fad-dar-oki
 ..      ..
 ..      ..
 ..      ..

我需要计算每一行的滚动平均值。因此对于数据框s,每行的滚动平均值将表示为s.meanR 中是否有可以计算 rolling-mean 的内置函数?我尝试了以下方法:

rollapply(data)

但它会引发错误argument "width" is missing, with no default。我无法理解这个错误以及width 的含义

【问题讨论】:

  • 您可以使用来自zoorollmean。使用rollapply,您需要传递函数和宽度参数。有疑问可以查看?rollapply的文档。 width - numeric vector or list. In the simplest case this is an integer specifying the window width (in numbers of observations) which is aligned to the original sample according to the align argument. Alternatively, width can be a list regarded as offsets compared to the current time, see below for details.
  • @akrun 我已经导入了包,但是不知道怎么用。
  • @akrun 你能举个例子作为答案吗?
  • 您可能需要传递列名而不是完整的数据框。您的预期输出是什么?
  • @RonakShah 你是怎么把它称为重复的?任何与moving mean 相关的问题都不能重复。

标签: r


【解决方案1】:

我们可以使用rollmeanrollapply 获得相同的输出

library(zoo)
rollmean(df1$Value, k = 3)
#[1]  0.13677590  0.12419375  0.22781866  0.17661827  0.51935576  0.08137071 -0.29009330 -0.43751774
rollapply(df1$Value, width = 3, FUN = mean)
#[1]  0.13677590  0.12419375  0.22781866  0.17661827  0.51935576  0.08137071 -0.29009330 -0.43751774

数据

set.seed(24)
df1 <- data.frame(Value = rnorm(10))

【讨论】:

  • rollmean 和 rollapply 中的3 是什么?
  • @Jatt 更新了帖子
  • width = 3 是什么意思?我无法理解这一点。你是怎么来到 3 的?
  • rollapply for sd 工作正常!
  • 它应该用abs 包裹,即abs((6*df$sd + df$mean) | (df$mean - 6*df$sd))
猜你喜欢
  • 2015-08-02
  • 2015-09-10
  • 2020-04-02
  • 1970-01-01
  • 1970-01-01
  • 2017-12-04
  • 2022-01-11
  • 2020-07-12
  • 2022-01-14
相关资源
最近更新 更多