理解本例中的R语法

理解本例中的R语法,r,dataset,stackexchange,R,Dataset,Stackexchange,嗨 我在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 <- whic

我在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)

y.max以下是该代码的翻译。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")
所以
nonPositiveDelta
是一个向量,类似于真-假-假。。。每个delta元素都有一个元素,指示delta的哪些元素是非正的

# vector containing the index of each element of delta that's <= 0
indicesOfNonPositiveDeltas <- which(nonPositiveDelta)
最后,结果存储在一个列表中。列表有点像数组数组,其中列表的每个元素本身可以是另一个列表或任何其他类型。在本例中,列表的每个元素都是一个向量

# 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

在没有看到代码的其余部分或它应该做什么的描述的情况下,我不得不猜测一下,但希望这能帮助您

谢谢你的详细解释。注释中列出了完整的线程,
align=“center”
rollapply
的默认值,因此可以省略该参数。
# 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