代码之家  ›  专栏  ›  技术社区  ›  evam

R: 以开头的所有列的总和

  •  0
  • evam  · 技术社区  · 3 年前

    我想创建一个新列,它是以“m\u0”开头的所有列的总和,并创建一个新列,它是以“w\u0”开头的所有列的总和。 不幸的是,它不是每n列一列,所以索引所有奇偶列将不起作用。

    columnnames <- c("m_16", "w_16", "w_17", "m_17", "w_18", "m_18")
    values1 <- c(3, 4, 8, 1, 12, 4)
    values2 <- c(8, 0, 12, 1, 3, 2)
    df <- as.data.frame(rbind(values1, values2))
    names(df) <- columnnames
    

    我想得到的是:

    columnnames <- c("m_16", "w_16", "w_17", "m_17", "w_18", "m_18", "sum_m", "sum_w")
    values1 <- c(3, 4, 8, 1, 12, 4, 8, 24)
    values2 <- c(8, 0, 12, 1, 3, 2, 11, 15)
    df <- as.data.frame(rbind(values1, values2))
    
    names(df) <- columnnames
    

    到目前为止,在搜索过程中,我只找到了如何根据条件对特定列求和,但我不想指定列,因为有很多列。

    提前感谢您的帮助!

    3 回复  |  直到 3 年前
        1
  •  2
  •   bash1000    3 年前

    dplyr 有一个快速的答案:

    library(dplyr)
    df <- df %>% 
        mutate(
            m_col_sum = select(., starts_with("m")) %>% rowSums(),
            w_col_sum = select(., starts_with("w")) %>% rowSums()
        )
    

    您可能需要指定 na.rm = TRUE 作为 rowSums()

        2
  •  2
  •   PaulS    3 年前

    另一种可能的解决方案:

    library(dplyr)
    
    df %>% 
      mutate(sum_m = across(starts_with("m")) %>% rowSums) %>% 
      mutate(sum_w = across(starts_with("w")) %>% rowSums)
    
    #>         m_16 w_16 w_17 m_17 w_18 m_18 sum_m sum_w
    #> values1    3    4    8    1   12    4     8    24
    #> values2    8    0   12    1    3    2    11    15
    
        3
  •  1
  •   hello_friend    3 年前
    # Vector containing the letters which target vectors' 
    # names start with: names_start_with => character vector
    names_start_with <- c("m", "w")
    
    # Compute row-sums, column-bind vectors to data.frame: res => data.frame
    res <- cbind(
      df,
      vapply(
        names_start_with, 
        function(x){
          rowSums(df[,startsWith(names(df), x)])
        }, 
        numeric(length(names_start_with))
      ),
      row.names = NULL
    )
    
    # Output data.frame to console: data.frame => stdout(console)
    res