0

Looking to do something that (I assume is pretty basic) using R. I have a very long dataset that looks like this:

 Country  A  B  C  D
 Austria  1  1  4  1
 Austria  5  2  6  1
 Austria  2  8  1  2
 Belgium  6  9  9  3
 Belgium  8  1  9  2

I want to be able to Merge all of the rows with the same Country, and sum all of the numbers within the respective columns, so it looks something like this:

 Country  A  B  C  D
 Austria  8  11 11 4
 Belgium  14 10 18 5

Thanks for your help!

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81

3 Answers3

0
dat %>% 
    group_by(Country) %>% 
    summarise(across(A:D, sum))
# A tibble: 2 × 5
  Country     A     B     C     D
  <chr>   <int> <int> <int> <int>
1 Austria     8    11    11     4
2 Belgium    14    10    18     5
user438383
  • 5,716
  • 8
  • 28
  • 43
0

Base R:

 aggregate(. ~ Country, data = df, sum)
  Country  A  B  C D
1 Austria  8 11 11 4
2 Belgium 14 10 18 5

With data.table:

library(data.table)
data.table(df)[, lapply(.SD, sum), by=Country ]

   Country  A  B  C D
1: Austria  8 11 11 4
2: Belgium 14 10 18 5

In a dplyr way:

library(dplyr)
     df %>%
     group_by(Country) %>%
     summarise_all(sum)

# A tibble: 2 x 5
  Country     A     B     C     D
  <chr>   <int> <int> <int> <int>
1 Austria     8    11    11     4
2 Belgium    14    10    18     5

With data:

     df <-  read.table(text = ' Country  A  B  C  D
    Austria  1  1  4  1
    Austria  5  2  6  1
    Austria  2  8  1  2
    Belgium  6  9  9  3
    Belgium  8  1  9  2', header = T)
s__
  • 9,270
  • 3
  • 27
  • 45
0

You can use rowsum to sum up rows per group.

rowsum(df[-1], df[,1])
#         A  B  C D
#Austria  8 11 11 4
#Belgium 14 10 18 5
GKi
  • 37,245
  • 2
  • 26
  • 48