sum columns with similar names in R

前端 未结 4 1872
梦谈多话
梦谈多话 2021-01-14 17:02

I\'ve got a dataframe that\'s got lots of columns that are something like this:

data <- data.frame (a.1 = 1:5, a.2b = 3:7, a.5 = 5:9, bt.16 = 4:8, bt.1234         


        
4条回答
  •  有刺的猬
    2021-01-14 17:31

    Here's another tidyverse solution:

    library(tidyverse)
    
    t(data) %>%
      data.frame() %>%
      group_by(., id = gsub('\\..*', '', rownames(.))) %>%
      summarise_all(sum) %>%
      data.frame() %>%
      column_to_rownames(var = 'id') %>%
      t()
    

    Result:

        a bt
    X1  9 11
    X2 12 13
    X3 15 15
    X4 18 17
    X5 21 19
    

提交回复
热议问题