【问题标题】:Sum rows in a column based on a condition in R根据R中的条件对列中的行求和
【发布时间】:2020-12-09 11:11:07
【问题描述】:

我想总结 Col1 中 Col2 等于 0 的行。并将总和添加到零之后的第一个值。我在下面展示一个例子。我在数据框中有不同的产品。

Date <- seq(as.Date("2021-01-01"), as.Date("2021-01-07"), by = "day")
Product<-rep("A",7)
Col1 <- c(2, 5, 1, 3, 2, 1, 2)
Col2 <- c(40, 0, 0, 0, 0, 0, 50)
Expected <- c(40, 0, 0, 0, 0, 0, 62)
TD <- data.frame(Date, Product, Col1, Col2, Expected)

【问题讨论】:

    标签: r dataframe dplyr count


    【解决方案1】:

    这是否可行:我已按产品分组,以防您的实际数据具有这种结构。

    library(dplyr)
    TD %>% group_by(Product) %>% mutate(sumval = sum(Col1[Col2 == 0])[1]) %>% 
    mutate(Expected = Col2) %>%  
    mutate(Expected = case_when((Col2 != 0 & lag(Col2) == 0) ~  Expected + sumval, TRUE ~ Expected )) %>% 
    select(-sumval)
    # A tibble: 7 x 5
    # Groups:   Product [1]
      Date       Product  Col1  Col2 Expected
      <date>     <chr>   <dbl> <dbl>    <dbl>
    1 2021-01-01 A           2    40       40
    2 2021-01-02 A           5     0        0
    3 2021-01-03 A           1     0        0
    4 2021-01-04 A           3     0        0
    5 2021-01-05 A           2     0        0
    6 2021-01-06 A           1     0        0
    7 2021-01-07 A           2    50       62
    

    【讨论】:

      【解决方案2】:

      一个dplyr 选项可以是:

      TD %>%
       group_by(Product) %>%
       mutate(Expected = if_else(row_number() == which(Col2 != 0 & lag(Col2, default = first(Col2)) == 0),
                                 Col2 + sum(Col1[Col2 == 0]),
                                 Col2))
      
        Date       Product  Col1  Col2 Expected
        <date>     <fct>   <dbl> <dbl>    <dbl>
      1 2021-01-01 A           2    40       40
      2 2021-01-02 A           5     0        0
      3 2021-01-03 A           1     0        0
      4 2021-01-04 A           3     0        0
      5 2021-01-05 A           2     0        0
      6 2021-01-06 A           1     0        0
      7 2021-01-07 A           2    50       62
      

      【讨论】:

        猜你喜欢
        • 2023-01-16
        • 1970-01-01
        • 2021-07-04
        • 1970-01-01
        • 2023-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-30
        相关资源
        最近更新 更多