【问题标题】:Summing over variables with certain pattern in dplyr mutate在 dplyr mutate 中对具有特定模式的变量求和
【发布时间】:2016-11-29 08:24:21
【问题描述】:

我有一个包含多个变量的 data.frame,我需要根据它们名称中的模式对它们进行求和。更具体地说,我的股票总和为 1,不包括我需要找出的可能的残差。我为此使用dplyr

一个示例数据帧:

 df <- data.frame(year = c(2000, 2001, 2002),
             aShare = c(.1,.2,.3),
             bShare = c(.3,.4,.5))

我尝试过像这样使用ends_with 函数:

tmp <- df %>% mutate(otherShare = 1 - sum(ends_with("Share")))

但它不会产生所需的结果:

TMP <- df %>% mutate(otherShare = 1 - (aShare + bShare))

【问题讨论】:

    标签: r dataframe dplyr


    【解决方案1】:

    有基础R

    df$x <-1- rowSums(df[colnames(df)[grepl("Share",colnames(df))]])
    

    使用半 dplyr :P

    df$x = (1-df %>% select(ends_with("Share")) %>% rowSums())
    

    【讨论】:

    • 另一种变体:df %&gt;% mutate(otherShare = 1 - select(., ends_with("Share")) %&gt;% rowSums())
    【解决方案2】:

    可能不是最好的选择,但我们可以按行使用apply

    df$otherShare <- apply(df[grep("Share$", names(df))], 1, function(x) 1 - sum(x))
    
    #   year aShare bShare otherShare
    #1 2000    0.1    0.3        0.6
    #2 2001    0.2    0.4        0.4
    #3 2002    0.3    0.5        0.2
    

    【讨论】:

      猜你喜欢
      • 2018-08-30
      • 2018-05-06
      • 2021-10-15
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 2019-01-29
      相关资源
      最近更新 更多