sum columns with similar names in R

前端 未结 4 1906
梦谈多话
梦谈多话 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:27

    You can try

    library(tidyverse)
    data.frame (a.1 = 1:5, a.2b = 3:7, a.5 = 5:9, bt.16 = 4:8, bt.12342 = 7:11) %>% 
      rownames_to_column() %>% 
      gather(k, v, -rowname) %>% 
      separate(k, letters[1:2]) %>% 
      group_by(rowname, a) %>% 
      summarise(Sum=sum(v)) %>% 
      spread(a, Sum)
    #> # A tibble: 5 x 3
    #> # Groups:   rowname [5]
    #>   rowname     a    bt
    #>       
    #> 1 1           9    11
    #> 2 2          12    13
    #> 3 3          15    15
    #> 4 4          18    17
    #> 5 5          21    19
    

    Created on 2018-04-16 by the reprex package (v0.2.0).

提交回复
热议问题