6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rで前後の幅が自由に変更できる移動平均をつくる

Posted at

移動平均を取るときに前後の幅を自由に変更したいが、ある程度のスピードは保証したい

猿みたいにforで移動平均を取ることもできますが、それはあまりに遅い為、なるべくベクトル演算でやります。
とはいえ適当なコードなので、もっと良い移動平均があったらぜひ教えてください。※変数名はくそコードと言われても仕方がないレベルです。
ちなみにNAは無いものとして扱います。(平均を取るときの母数にも含めない)

ma.r
ma.ba <- function(data, lmb=10, lma=10){
  length <- length(data)
  df.t <- ifelse(is.na(data),0,1)
  df.a <- ifelse(is.na(data),0,data)
  df.b <- df.a
  df.c <- df.t
  for(i in 1:lmb){ # before
    df.b <- df.b + c(rep(0,i), df.a[1:(length - i)])
    df.c <- df.c + c(rep(0,i), df.t[1:(length - i)])
  }
  for(i in 1:lma){ # after
    df.b <- df.b + c(df.a[(i + 1):length], rep(0,i))
    df.c <- df.c + c(df.t[(i + 1):length], rep(0,i))
  }
  df.b/df.c
}

使用例:

usage.r
df <- data.frame(a=1:20000)
df$a <- ifelse((-1)^df$a==1, NA, df$a)
df$b <- ma.ba(df$a)
df$c <- ma.ba(df$a, 3, 1)

df.png

NAが混ざっていても安心ですね。

6
4
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?