How to find the sum of every n values in R data frame columns?


To find the sum of every n values in R data frame columns, we can use rowsum function along with rep function that will repeat the sum for rows. For example, if we have a data frame called df that contains 4 columns each containing twenty values then we can find the column sums for every 5 rows by using the command rowsum(df,rep(1:5,each=4)).

Example

Consider the below data frame −

 Live Demo

x1<-rpois(20,5)
x2<-rpois(20,2)
df1<-data.frame(x1,x2)
df1

Output

   x1 x2
1  7  3
2  9  4
3  7  3
4  3  3
5  9  1
6  4  1
7  7  3
8  4  3
9  6  3
10 5  0
11 4  4
12 5  4
13 5  1
14 6  2
15 1  3
16 1  2
17 6  1
18 6  2
19 1  2
20 8  2

Finding the column sums for every 5 rows in df1 −

Example

rowsum(df1,rep(1:5,each=4))

Output

  x1 x2
1 26  13
2 24   8
3 20  11
4 13   8
5 21   7

Example

 Live Demo

y1<-rnorm(20)
y2<-rnorm(20)
y3<-rnorm(20)
df2<-data.frame(y1,y2,y3)
df2

Output

      y1           y2           y3
1  -0.46478980   0.61742170  -0.21406143
2   1.42820694  -1.68668632  -1.69183062
3  -1.09014651  -0.80538397  -1.73060665
4   0.04143155  -0.86250648  -0.50698176
5   1.31066192   1.98317492   0.81144732
6   1.05362995   1.31032857  -0.48538293
7   1.13221772   3.27862204  -1.42116882
8  -2.30864576  -0.02998736  -0.35898649
9  -1.30371212   0.26152070  -0.25968593
10 -0.93208053   0.59726153   0.31393063
11  0.23612475   1.72240765  -2.21882009
12  0.58740869   0.53739269   0.52578465
13  0.42427296  -0.84617072  -0.35684917
14 -0.33885432   0.09297437  -0.61340922
15 -0.40246042  -0.94370468   0.01108134
16 -0.97853686   1.08559425   0.71596796
17  0.28577367  -0.57999260  -0.14349388
18 -0.78154458  -2.40582173   2.50692776
19  0.05791671   0.94479521   0.79723502
20 -0.03289249  -1.46621425  -0.89169830

Example

Finding the column sums for every 5 rows in df2 −

rowsum(df2,rep(1:5,each=4))

Output

        y1          y2          y3
1  -0.08529781  -2.7371551  -4.1434804
2   1.18786383   6.5421382  -1.4540909
3  -1.41225921   3.1185826  -1.6387907
4  -1.29557865  -0.6113068  -0.2432091
5  -0.47074670  -3.5072334   2.2689706

Updated on: 16-Mar-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements