【问题标题】:How to replace an empty output from dplyr::filter()如何替换 dplyr::filter() 的空输出
【发布时间】:2020-06-25 18:02:13
【问题描述】:

我有一个数据集dt,其中有一列名为x,其中包含数字和意外值。我的目标是使用dplyr::filter() 函数从基于x 的值的查找表中检索一个值,而不清理x(因为存在意外值)。如果在查找表中找不到条件语句,dplyr::filter() 返回一个空 tibble,我想将此输出替换为 0.0 的值作为数组。

这是我的代码示例:

dt <- tibble(x = c(0, -1, 0.5))
lookup_table <- tibble(
         lower_bound = c(0, 0.2, 0.5),
         upper_bound = c(0.2, 0.5, 1000000),
         output = c(0.1, 0.2, 0.3)
        )
y <- lookup_table %>% filter(lower_bound <= dt$x, upper_bound > dt$x) %>% select(output) %>% pull() %>% if_else(length() != 0, lookup_table %>% filter(lower_bound <= dt$x, upper_bound > dt$x) %>% select(output) %>% pull(), 0.0)
y
>>> [1]  0.1 0.0 0.3 # Expected output

谢谢你,

约翰

编辑:请注意dt 和查找表的行数不一定相同。

【问题讨论】:

    标签: r filter dplyr tibble


    【解决方案1】:

    x 拉到小标题中然后使用if_else 创建一个包含所需输出的新列可能会更容易一些。

    library(dplyr)
    dt <- tibble(x = c(0, -1, 0.5))
    lookup_table <- tibble(
             lower_bound = c(0, 0.2, 0.5),
             upper_bound = c(0.2, 0.5, 1000000),
             output = c(0.1, 0.2, 0.3)
            )
    # Create column with output  
    lookup_table <- lookup_table %>% 
      bind_cols(dt) %>% 
      mutate(y = if_else(lower_bound <= x & upper_bound > x, output, 0))
    
    lookup_table %>% pull(y)
    # [1] 0.1 0.0 0.3
    

    【讨论】:

    • 嗨@Chris,Dt 的长度不一定与lookup_table 相同。您的解决方案不会一直有效!
    • 如果 dtlookup_table 表有不同的长度,我认为你需要一个共同的标识符跨越两者 - 否则将无法判断 dt 的哪个元素与哪个间隔相关lookup_table。如果有一个向量或列将两者联系起来,那么您可以合并并遵循相同的过程。
    【解决方案2】:

    我想我找到了解决方案。我们可以将findIntervalgsub R 函数与dplyrtidyr 包组合在一起。

    library(dplyr)
    library(tidyr)
    
    
    dt <- tibble(x = c(0, -1, 0.5))
    lookup_table <- tibble(
             lower_bound = c(0, 0.2, 0.5),
             upper_bound = c(0.2, 0.5, 1000000),
             output = c(0.1, 0.2, 0.3)
            )
    y <- arrange(lookup_table, lower_bound)[as.numeric( dt$x %>% findInterval(lookup_table %>% arrange(lower_bound) %>% select( lower_bound ) %>% pull() ) %>% gsub(pattern=0, replacement=NA)), 'output'] %>% pull() %>% replace_na(0)
    y
    >>> [1]  0.1 0.0 0.3 # Actual output
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多