【问题标题】:Find min and max of a column given an ordered index in Dplyr在 Dplyr 中查找给定有序索引的列的最小值和最大值
【发布时间】:2021-12-30 10:04:14
【问题描述】:

我有一个向量,我添加他的索引如下:

library(tidyverse)
## Create the vector
vector_ex <- c(44, 30, 24, 32, 35)
## Add indexes 
vector_ex_indexed <- cbind( seq_along(vector_ex), vector_ex)

as.data.frame(vector_ex_indexed) %>%
  rename(Index = V1) 

  Index vector_ex
1     1        44
2     2        30
3     3        24
4     4        32
5     5        35

考虑到索引的顺序,我想找到vector_ex第一个 最小值和vector_ex 之后的第一个 最大值附加到最小值的索引。

例如在这种情况下,我想用 dplyr 来识别:

  • 具有最小值的第一对Index & vector_ex 是:

    Index vector_ex
    3     3        24
    
  • 第一对Index & vector_ex的最大值是:

    Index vector_ex
    5     5        35
    

【问题讨论】:

  • 请更准确地解释索引和您的向量的相互作用。使用您的示例数据,完全不清楚为什么第一个最大值是 5 / 35 而不是 1/44。那么你想得到vector_ex的最大值/最小值还是索引?还是某种组合?或者索引组的向量 x 的最小值/最大值?还是别的什么?
  • 给定索引顺序的第一个最小值将是索引 3 处的 24;随后的第一个最大值(在索引 3 之后)在 5 处为 35。我将查找第一个局部最小值及其索引以及该索引之后的第一个最大值。通过这种方式,我将在给定索引顺序的最小值和最大值的情况下获得最大差异。

标签: r dplyr tidyverse


【解决方案1】:

一个选项可能是:

df %>%
    slice(which.min(vector_ex):n()) %>%
    slice(c(1, which.max(vector_ex)))

  Index vector_ex
1     3        24
2     5        35

【讨论】:

    【解决方案2】:

    另一个解决方案是filter:

    library(tidyverse)
    df %>%
      filter(vector_ex == min(vector_ex) |
             vector_ex == max(vector_ex[Index > Index[which.min(vector_ex)]]))
    
      Index vector_ex
    1     3        24
    2     5        35
    

    【讨论】:

      猜你喜欢
      • 2017-05-30
      • 2021-08-17
      • 2013-06-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 2017-05-08
      • 1970-01-01
      • 2015-06-29
      相关资源
      最近更新 更多