-2

データセット内のピークを見つける - R を使用

やあ

このスレッドをstackexchangeで見ました。私は R プログラマーではありません (まだ)。しかし、Cで実装したいのですが、Rの構文に慣れていないため、コードを理解できません。y.max や i.max などの配列を作成していることは知っていますが、実行された操作と配列の操作方法はわかりません。特に気になったのは以下の4行です。

  y.max <- rollapply(zoo(y.smooth), 2*w+1, max, align="center")
  delta <- y.max - y.smooth[-c(1:w, n+1-1:w)]
  i.max <- which(delta <= 0) + w
  list(x=x[i.max], i=i.max, y.hat=y.smooth)

これらの特定の構文を理解するためのいくつかの指針が役立ちます。

4

1 に答える 1

0

これがそのコードの翻訳です。R はネストされた関数呼び出しをよく使用しますが、各関数が何をするかを知らなければ理解するのが難しい場合があります。これを支援するために、いくつかの行を複数の行に分割し、結果を新しい変数に保存しました。

# convert y.smooth to a zoo (time series) object
zoo_y.smooth <- zoo(y.smooth)

# divide the data into rolling windows of width 2*w+1
# get the max of each window
# align = "center" makes the indices of y.max be aligned to the center
# of the windows
y.max <- rollapply(zoo_y.smooth, 
                   width = 2*w+1, 
                   FUN = max, 
                   align="center")

R のサブセット化は非常に簡潔になる可能性があります。c(1:w, n+1-1:w)と呼ばれる数のベクトルを作成しますtoExclude。を使用してそのベクトルを-サブセット化演算子に渡すと、で指定されたインデックスの[]要素を除く のすべての要素が選択されます。を省略すると、逆になります。y.smoothtoExclude-

# select all of the elements of y.smooth except 1 to w and n+1-1 to w
toExclude <- c(1:w, n+1-1:w)
subset_y.smooth <- y.smooth[-toExclude]

# element-wise subtraction
delta <- y.max - subset_y.smooth

# logical vector the same length of delta indicating which elements
# are less than or equal to 0
nonPositiveDelta <- delta <= 0

TRUE FALSE FALSE ...nonPositiveDeltaのようなベクトルも同様で、delta の各要素の要素を持ち、delta のどの要素が正でないかを示します。

# vector containing the index of each element of delta that's <= 0
indicesOfNonPositiveDeltas <- which(nonPositiveDelta)

indicesOfNonPositiveDeltas一方、TRUE だった前のベクトルのすべての要素のインデックスを含む 1、3、4、5、8 のようなベクトルです。

# indices plus w
i.max <- indicesOfNonPositiveDeltas + w

最後に、結果がリストに格納されます。リストは配列の配列のようなもので、リストの各要素自体が別のリストまたはその他のタイプになることができます。この場合、リストの各要素はベクトルです。

# create a three element list 
# each element is named, with the name to the left of the equal sign
list(
  x=x[i.max], # the elements of x at indices specified by i.max
  i=i.max, # the indices of i.max
  y.hat=y.smooth) # the y.smooth data

コードの残りの部分や、それが何をするべきかについての説明を見ていないので、少し推測する必要がありましたが、これが役に立てば幸いです。

于 2015-02-01T00:24:39.167 に答える