【问题标题】:In R, how can I filter based on the maximum value in each row of my data?在 R 中,如何根据数据每行中的最大值进行过滤?
【发布时间】:2019-12-14 13:30:54
【问题描述】:

我有一个包含 19 列纯数字数据的 tibble(或数据框,如果您愿意的话),我想将其过滤到至少有一个值高于或低于阈值的行。我更喜欢 tidyverse/dplyr 解决方案,但不管用什么都可以。

这与this question 相关,但在我看来至少有两种不同的方式:

  1. 我没有标识符列(除了行号,我想)
  2. 我需要根据正在评估的当前行中的最大值进行子集化,而不是跨列进行子集化

以下是我尝试过的尝试:

data %>% filter(max(.) < 8)
data %>% filter(max(value) < 8)
data %>% slice(which.max(.))

【问题讨论】:

标签: r dplyr


【解决方案1】:

这是一种保持行的值高于阈值的方法。为了使值保持在阈值以下,只需反转 any 中的不等式 -

data %>% 
  filter(apply(., 1, function(x) any(x > threshold)))

实际上,@r2evans 在 cmets 中有更好的答案 -

data %>%
  filter(rowSums(. > threshold) >= 1)

【讨论】:

    【解决方案2】:

    结合更多应该可以很好扩展的选项:

    library(dplyr)
    
    # a more dplyr-y option 
    iris %>%
          filter_all(any_vars(. > 5))
    
    # or taking advantage of base functions
    iris %>%
          filter(do.call(pmax, as.list(.))>5)
    

    【讨论】:

    • 不知道any_vars。好的! +1
    【解决方案3】:

    也许有更好更有效的方法,但是如果我理解正确的话,这两个功能应该可以满足您的需求。此解决方案假定您只有数字数据。

    • 您转置 tibble(因此您获得了一个数字矩阵)
    • 然后您使用 map 来获取按列的最大值或最小值(即初始数据集中按行的最大值/最小值)。
    • 您获得了您要查找的行索引
    • 最后,您可以过滤数据集。
    
    # Random Data -------------------------------------------------------------
    
    data <- as.tibble(replicate(10, runif(20)))
    
    # Threshold to be used -----------------------------------------------------
    
    max_treshold = 0.9
    min_treshold = 0.1
    
    # Lesser_max --------------------------------------------------------------
    
    lesser_max = function(data, max_treshold = 0.9) {
      index_max_list =
        data %>%
        t() %>%
        as.tibble() %>%
        map(max) %>%
        unname()
    
      index_max =
        index_max_list < max_treshold
    
      data[index_max,]
    }
    
    # Greater_min -------------------------------------------------------------
    
    greater_min = function(data, min_treshold = 0.1) {
      index_min_list =
        data %>%
        t() %>%
        as.tibble() %>%
        map(min) %>%
        unname()
    
      index_min =
        index_min_list > min_treshold
    
      data[index_min,]
    }
    
    # Examples ----------------------------------------------------------------
    
    data %>%
      lesser_max(max_treshold)
    
    data %>%
      greater_min(min_treshold)
    
    

    【讨论】:

      【解决方案4】:

      我们可以使用base R方法

      data[Reduce(`|`, lapply(data, `>`, threshold)),]`
      

      【讨论】:

        猜你喜欢
        • 2018-01-07
        • 2016-07-01
        • 2022-01-17
        • 1970-01-01
        • 2016-10-05
        • 2021-03-14
        • 2021-07-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多