R: how to check whether a vector is ascending/descending

前端 未结 2 882
被撕碎了的回忆
被撕碎了的回忆 2021-02-12 20:31
vector1 = c(2, 2, 2, 2, 2, 2)
vector2 = c(2, 2, 3, 3, 3, 3)
vector3 = c(2, 2, 1, 2, 2, 2)

I want to know if the numbers in the vector are ascending/sta

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-12 21:06

    You can diff to compute the differences between elements and all to check if they are all non-negative:

    all(diff(vector1) >= 0)
    # [1] TRUE
    all(diff(vector2) >= 0)
    # [1] TRUE
    all(diff(vector3) >= 0)
    # [1] FALSE
    

    The above code checks if all the vectors are non-decreasing, and you could replace >= 0 with <= 0 to check if they're non-increasing. If instead your goal is to identify vectors that are either non-decreasing or non-increasing (aka they don't have an increasing and a decreasing step in the same vector), there's a simple modification:

    !all(c(-1, 1) %in% sign(diff(vector1)))
    # [1] TRUE
    !all(c(-1, 1) %in% sign(diff(vector2)))
    # [1] TRUE
    !all(c(-1, 1) %in% sign(diff(vector3)))
    # [1] FALSE
    

提交回复
热议问题