【问题标题】:How do you subtract two columns in a data frame IF they exist in the data frame?如果它们存在于数据框中,如何减去数据框中的两列?
【发布时间】:2022-06-16 16:08:50
【问题描述】:

我有一个带有值的数据框。我想mutate 减去的列到新列中。有时一列不存在,所以我希望它为存在的列运行和变异,如果不存在,不要失败,只做其余的列。几乎像mutate if exists

例如,

Df <- df %>% mutate(columnxdif = columnxbeg -columnxend, columnydif = columnybeg-columnyend)

如果columnxend 不存在,它仍将运行并返回columnydif 突变为df 上的新列。

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:

    使用示例数据总是更容易,但让我们在这里做一个与您的数据描述相匹配的小例子:

    df <- data.frame(columnxbeg = 1:5, columnxend = 6:10,
                     columnybeg = 2:6, columnyend = 8:12)
    
    df
    #>   columnxbeg columnxend columnybeg columnyend
    #> 1          1          6          2          8
    #> 2          2          7          3          9
    #> 3          3          8          4         10
    #> 4          4          9          5         11
    #> 5          5         10          6         12
    

    要在单个管道中执行此操作,我们需要找到后缀为“beg”的列和后缀为“end”的列,确保它们的顺序正确,减去它们,然后将它们绑定到现有数据:

    library(tidyverse)
    
    df %>%
      bind_cols(((df %>%
        select(ends_with("beg")) %>%
        select(order(names(.)))) -
        (df %>%
        select(ends_with("end")) %>%
        select(order(names(.))))) %>%
        rename_with(~str_replace(.x, "beg", "diff")))
    #>   columnxbeg columnxend columnybeg columnyend columnxdiff columnydiff
    #> 1          1          6          2          8          -5          -6
    #> 2          2          7          3          9          -5          -6
    #> 3          3          8          4         10          -5          -6
    #> 4          4          9          5         11          -5          -6
    #> 5          5         10          6         12          -5          -6
    

    这适用于任意数量的列,只要它们具有一致的命名模式。

    reprex package (v2.0.1) 于 2022-06-06 创建

    【讨论】:

      猜你喜欢
      • 2018-06-29
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 2018-08-29
      • 1970-01-01
      • 2014-07-03
      • 1970-01-01
      • 2020-12-27
      相关资源
      最近更新 更多