计算R中向量中的“方向变化”

时间:2019-12-15 19:05:43

标签: r vector

我需要计算一个变量反转其增长方式的次数-从增加值到减少值(以及从减少值到增加值)。在下面的示例中,我应该能够找到4个这样的反演。如何创建一个新的虚拟变量来显示这种反转?

x <- c(1:20,19:5,6:15,12:9,10:11)
plot(x)

A vector with 4 "change in direction"

2 个答案:

答案 0 :(得分:2)

您实际上是在问“ x的二阶导数何时不等于零?”,因此您可以进行双倍差分:

x <- c(1:20,19:5,6:15,12:9,10:11)
plot(seq_along(x), x)
changes <- c(0, diff(diff(x)), 0) != 0

要显示它选择了正确的点,请将它们涂成红色。

points(seq_along(x)[changes], x[changes], col = "red")

答案 1 :(得分:0)

此函数将返回方向改变的索引:

get_change_indices <- function(x){
  # return 0 if x contains one (or none, if NULL) unique elements
  if(length(unique(x)) <= 1) return(NULL)

  # make x named, so we can recapture its indices later
  x <- setNames(x, paste0("a", seq_along(x)))

  # calculate diff between successive elements
  diff_x <- diff(x)

  # remove points that are equal to zero
  diff_x <- diff_x[!diff_x==0]

  # identify indices of changepoints
  diff_x <- c(diff_x[1], diff_x)
  change_ind <- NULL
  for(i in 2:length(diff_x)){
    if(sign(diff_x[i]) != sign(diff_x[i-1])){
      change_ind_curr <- as.numeric(gsub("a", "", names(diff_x[i]))) - 1
      change_ind <- c(change_ind, change_ind_curr)
    } 
  }

  change_ind
}

其输出的长度是更改的次数。

请注意,当x中的更改为非线性(例如, x <- c(1, 4, 9, 1)