Combining and Taking the Averages of Rows

Hello, I am trying to take group two rows and take the averages of their values in their respective columns.

I have 10 rows of data that I want to group into sets of 2 to end up with 5 rows of data:
A B C D

  1. Afghanistan 66
  2. Bangladesh 74
  3. Barbados 80
  4. Belize.
  5. China
  6. DR
  7. Ghana
  8. Guatemala
  9. Kenya
  10. Yemen

And end up having
Afghanistan and Bangladesh Average of A Avg of B Avg of C Avg of D

I would also want to rename the combined row into something else.

Thank you!

Here is one way to average pairs of rows.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
#Invent data
DF <- data.frame(Country = c("Afgan", "Bang", "Barb", "belize", "China",
                             "DR", "Ghana", "Guat", "Kenya", "Yemen"),
                 A = round(runif(n = 10, min = 50, max = 100)),
                 B = round(runif(n = 10, min = 50, max = 100)),
                 C = round(runif(n = 10, min = 50, max = 100)),
                 D = round(runif(n = 10, min = 50, max = 100)))
DF
#>    Country  A   B  C  D
#> 1    Afgan 51  79 98 66
#> 2     Bang 92  60 75 71
#> 3     Barb 72  77 80 98
#> 4   belize 83  95 72 55
#> 5    China 52 100 94 74
#> 6       DR 74  65 78 98
#> 7    Ghana 70  58 65 89
#> 8     Guat 82  73 76 54
#> 9    Kenya 78  81 61 84
#> 10   Yemen 94  96 56 89

#Make a column to label the pairs of rows
DF <- DF |> mutate(Group = rep(LETTERS[1:5], each = 2))
DF
#>    Country  A   B  C  D Group
#> 1    Afgan 51  79 98 66     A
#> 2     Bang 92  60 75 71     A
#> 3     Barb 72  77 80 98     B
#> 4   belize 83  95 72 55     B
#> 5    China 52 100 94 74     C
#> 6       DR 74  65 78 98     C
#> 7    Ghana 70  58 65 89     D
#> 8     Guat 82  73 76 54     D
#> 9    Kenya 78  81 61 84     E
#> 10   Yemen 94  96 56 89     E
#Compute the averages of the groups
Averages <- DF |> group_by(Group) |> 
  summarize(across(.cols = -Country, .fns = mean))

Averages
#> # A tibble: 5 x 5
#>   Group     A     B     C     D
#>   <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 A      71.5  69.5  86.5  68.5
#> 2 B      77.5  86    76    76.5
#> 3 C      63    82.5  86    86  
#> 4 D      76    65.5  70.5  71.5
#> 5 E      86    88.5  58.5  86.5

Created on 2021-10-31 by the reprex package (v2.0.1)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.