【问题标题】:Finding a list of previous max values in order of a vector R按向量 R 的顺序查找先前最大值的列表
【发布时间】:2021-11-08 23:24:58
【问题描述】:

我想查找以前的最大值列表。所以对于一个向量: 3, 2,2,3,4,3,9,5,2,3,4,6,120,1 第一个最大值是 3,第二个最大值是 4(因为,4>3),然后是 9(因为 9>4),然后是 120(120>9) 因此,作为输出,我需要以下位置: 1,5,7,13

在没有 for 循环的情况下有没有办法做到这一点?

```
vector<-c(3, 2,2,3,4,3,9,5,2,3,4,6,120,1)
results<-1
max<-3
for(i in 2:length(vector)){
if(vector[i]>max{
results<-c(results, i)
max<-vector[i]}
else {next}
}
```

【问题讨论】:

  • 您为什么需要使用dplyr 完成这项工作?
  • match(unique(x &lt;- cummax(vector)), x)
  • with(rle(cummax(x)), which(sequence(lengths)==1)) 另一种奇怪的方式

标签: r dplyr tidyverse


【解决方案1】:

这可以通过行程编码来完成:

vec <- c(3,2,2,3,4,3,9,5,2,3,4,6,120,1)
r <- rle(cummax(vec))
c(1, 1+cumsum(r$lengths)[-length(r$lengths)])
# [1]  1  5  7 13

还有一个来自@user20650 的变体更短、更简洁(谢谢!):

which(as.logical(c(1, diff(cummax(vec)))))
# [1]  1  5  7 13

【讨论】:

  • 确实,简洁多了,很好。
【解决方案2】:

也许dplyrtibble 的另一种解决方案:

library(dplyr)
library(tibble)

cummax(vector) %>%
  enframe() %>%
  group_by(value) %>%
  slice_head() %>%
  pull(name)

[1]  1  5  7 13

【讨论】:

    【解决方案3】:

    另一种方法是使用递归函数

    findAllMaximums <- function(data, index = 1, results = c()){
        if(index == length(data)) return(results)
        if(index==1) return(findAllMaximums(data, index + 1, index))
        if(data[index] > max(data[results])) results = append(results, index)
        return(findAllMaximums(data, index + 1, results))
    }
    
    vector<-c(3, 2,2,3,4,3,9,5,2,3,4,6,120,1)
    
    print(findAllMaximums(vector))
    

    【讨论】:

      【解决方案4】:
      sapply(split(1:length(vector), cummax(vector)), `[`, 1)
      ##  3   4   9 120  <- the names of the result vector (=max values)
      ##  1   5   7  13  <- the values (=indexes)
      

      只取cummax() 分组中的第一个。

      【讨论】:

        猜你喜欢
        • 2016-10-27
        • 2015-10-11
        • 2020-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-10
        相关资源
        最近更新 更多