【问题标题】:Sum across rows but only the cells that meet a condition跨行求和,但仅满足条件的单元格
【发布时间】:2021-04-28 20:25:08
【问题描述】:

样本数据:

df <- tibble(x = c(0.1, 0.2, 0.3, 0.4),
             y = c(0.1, 0.1, 0.2, 0.3),
             z = c(0.1, 0.2, 0.2, 0.2))
df
# A tibble: 4 x 3
      x     y     z
  <dbl> <dbl> <dbl>
1   0.1   0.1   0.1
2   0.2   0.1   0.2
3   0.3   0.2   0.2
4   0.4   0.3   0.2

我想跨行求和,并且只想将满足特定逻辑条件的“单元格”相加。在此示例中,我只想按行将包含等于或大于指定阈值的单元格相加。

期望的输出

threshold <- 0.15
# A tibble: 4 x 4
      x     y     z cond_sum
  <dbl> <dbl> <dbl>    <dbl>
1   0.1   0.1   0.1      0  
2   0.2   0.1   0.2      0.4
3   0.3   0.2   0.2      0.7
4   0.4   0.3   0.2      0.9

伪代码

这是我脑海中的争论点。

df %>%
  rowwise() %>%
  mutate(cond_sum = sum(c_across(where(~ "cell" >= threshold))))

感谢整洁的解决方案!

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

    一个有效的选择是将低于阈值的值替换为 NA 并在rowSums 中使用na.rm 而不是rowwise/c_across

    library(dplyr)
    df %>% 
      mutate(cond_sum = rowSums(replace(., . < threshold, NA), na.rm = TRUE))
    

    -输出

    # A tibble: 4 x 4
    #      x     y     z cond_sum
    #  <dbl> <dbl> <dbl>    <dbl>
    #1   0.1   0.1   0.1      0  
    #2   0.2   0.1   0.2      0.4
    #3   0.3   0.2   0.2      0.7
    #4   0.4   0.3   0.2      0.9
    

    或者c_across

    df %>% 
      rowwise %>%
      mutate(cond_sum = {val <- c_across(everything())
                         sum(val[val >= threshold])}) %>%
      ungroup
    

    base R

    df$cond_sum <- rowSums(replace(df, df < threshold, NA), na.rm = TRUE)
    

    【讨论】:

      【解决方案2】:

      dplyrpurrr 的选项可以是:

      df %>%
       mutate(cond_sum = pmap_dbl(across(x:z), ~ sum(c(...)[c(...) > threshold])))
      
            x     y     z cond_sum
        <dbl> <dbl> <dbl>    <dbl>
      1   0.1   0.1   0.1      0  
      2   0.2   0.1   0.2      0.4
      3   0.3   0.2   0.2      0.7
      4   0.4   0.3   0.2      0.9
      

      或者只是使用dplyr:

      df %>%
       mutate(cond_sum = Reduce(`+`, across(x:z) * (across(x:z) > threshold)))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多