-2

在数据集中寻找峰值 - 使用 R

你好

我在stackexchange上看到了这个帖子。我不是 R 程序员(还)。但是我想用C实现。但是不熟悉R语法,我无法理解代码。我知道它会创建诸如 y.max 和 i.max 之类的数组,但我不确定已完成的操作以及它如何操作数组。以下是我特别感兴趣的四行。

  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.smooth除 中指定的索引处的元素之外的所有元素toExclude。省略-会适得其反。

# 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另一方面,是一个像 1, 3, 4, 5, 8 这样的向量,包含前一个向量中每个为 TRUE 的元素的索引。

# 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 回答