Create new group by summing of first 5 numbers for each groups

Hi Everyone,
I have a dataframe as provided below

Group=c(1,	1,	1,	2	,2,	3	,3,	3	,3,	3,	4	,4,	4,	4,	4,4,4,	5,	5	,5)
Temp=	c(0	,0.1,	0.2,	0	,0.1,	0	,0.2	,0.1,	0	,0.1,	0,	0.1,	0.5,	0.1	,0.1,	0,	0.1,	0,	0.1,	0.1)
DF = cbind(Group,Temp)

I want to create a new group in such a way that it sums the DF for the first 5 rows.
The expected output is

Group_new=c(1,	1,	1,	2	,2,	3	,3,	3	,3,	3,	4	,4,	4,	4,	4,5,	5	,6,6,6)
Temp_sum=c(0.3,	0.3	,0.3,	0.1	,0.1,	0.4	,0.4,	0.4	,0.4,	0.4,	0.9,	0.9,	0.9,
           0.9,	0.9	,0.1,	0.1,	0.2	,0.2,	0.2)

Df1 = cbind(Group_new,Temp,Temp_sum)

Thanks in advance.!

Is this what you are after? Keeping only the first five rows of each group, but showing the group sum?

library(tidyverse)
DF %>% 
  as_tibble() %>% 
  group_by(Group) %>% 
  mutate(temp_sum = sum(Temp)) %>% 
  slice(1:5) # first five rows of each group

# A tibble: 18 x 3
# Groups:   Group [5]
   Group  Temp temp_sum
   <dbl> <dbl>    <dbl>
 1     1   0        0.3
 2     1   0.1      0.3
 3     1   0.2      0.3
 4     2   0        0.1
 5     2   0.1      0.1
 6     3   0        0.4
 7     3   0.2      0.4
 8     3   0.1      0.4
 9     3   0        0.4
10     3   0.1      0.4
11     4   0        0.9
12     4   0.1      0.9
13     4   0.5      0.9
14     4   0.1      0.9
15     4   0.1      0.9
16     5   0        0.2
17     5   0.1      0.2
18     5   0.1      0.2
1 Like

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.