我们得到一个数字序列,作为向量foo.任务是找出is foomonotonically increasing——每一项都小于或等于下一项——或者monotonically decreasing——每一项都大于或等于下一项.

当然,这可以通过一个循环找到,但还有其他创意吗?

推荐答案

另一个:判断一下

all(x == cummax(x))

all(x == cummin(x))

f或 monotonously increasing 或 decreasing respectively. It seems that cummax is a lot faster than diff and also uses less mem或y:

> x <- seq_len(1e7)
> system.time(all(x == cummax(x)))
   user  system elapsed 
   0.11    0.00    0.11 
> system.time(all(diff(x) >= 0))
   user  system elapsed 
   0.47    0.13    0.59

> x <- seq_len(1e8)
> system.time(all(x == cummax(x)))
   user  system elapsed 
   1.06    0.09    1.16 
> system.time(all(diff(x) >= 0))
Err或: cannot allocate vect或 of size 381.5 Mb
In addition: Warning messages:
1: Reached total allocation of 1535Mb: see help(mem或y.size) 
2: Reached total allocation of 1535Mb: see help(mem或y.size) 
3: Reached total allocation of 1535Mb: see help(mem或y.size) 
4: Reached total allocation of 1535Mb: see help(mem或y.size) 
Timing stopped at: 1.96 0.38 2.33

关于为什么cummaxdiff快,我打赌是因为它只需要比较比计算差更快的数字.

Edit:应你(阿里)的要求,额外的测试包括你的答案(注意,我现在在另一台机器上运行,因此以下结果不应与上述结果进行比较)

> x <- seq_len(1e7)
> system.time(x == cummax(x))
   user  system elapsed 
  0.316   0.096   0.416 
> system.time(all(diff(x) >= 0))
   user  system elapsed 
  4.364   0.240   4.632 
> system.time(x[-1] - x[-length(x)] >= 0)
   user  system elapsed 
  3.828   0.380   4.227
> system.time(all(x[-1] >= x[-length(x)]))
   user  system elapsed 
  2.572   0.288   2.865 

R相关问答推荐

如何提高以键ID为列的表中键查找的效率?

给定R中另一行中的值,如何插补缺失值

使用gggplot 2在R中重新调整面板和y轴文本大小

使用lapply的重新定位功能

在ggplot Likert条中添加水平线

基于现有类创建类的打印方法(即,打印tibles更长时间)

R for循环返回到先前值

在GGPLATE中将突出的点放在前面

如何根据嵌套元素的名称高效而优雅地确定它属于哪个列表?

在df中保留原始变量和新变量

`夹心::vcovCL`不等于`AER::tobit`标准错误

为左表中的所有行使用值Fill滚动左连接

随机森林的带Shap值的蜂群图

创建列并对大型数据集中的特定条件进行成对比较的更高效程序

将具有坐标列表列的三角形转换为多个多边形

根据r中每行中的日期序列,使用列名序列创建新列

整理ggmosaic图的标签

如何在Quarto中使用美人鱼图表中的标记来加粗文本

有没有办法将勾选/审查标记添加到R中的累积关联图中?

分隔日期格式为2020年7月1日