这是该代码的翻译。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
在没有看到其余代码或它应该做什么的描述的情况下,我不得不猜测一下,但希望这可以帮助你。