I want to group my df by three columns and add a new row which will be a sum of a fourth column.
My data looks like
fc <- c("F", "F", "E", "E", "TF", "TF")
group_code <- c("Egg_x", "Egg_y", "Egg_x", "Egg_y", "Egg_x", "Egg_y")
id <- c(1, 1, 1, 1, 1, 1)
value <- c(2, 21, 4, 3, 20, 15)
df <-data.frame(cbind(fc, group_code, id, value))
> df
fc group_code id value
1 F Egg_x 1 2
2 F Egg_y 1 21
3 E Egg_x 1 4
4 E Egg_y 1 3
5 TF Egg_x 1 20
6 TF Egg_y 1 15
In this example I want to create a new group which will include both Egg_x
and Egg_y
, I can do this using df$group <- sub('\\_.*', '', df$group_code)
, we have
> df
fc group_code id value main_group
1 F Egg_x 1 2 Egg
2 F Egg_y 1 21 Egg
3 E Egg_x 1 4 Egg
4 E Egg_y 1 3 Egg
5 TF Egg_x 1 20 Egg
6 TF Egg_y 1 15 Egg
I want to add in a new row for each value of the fc
column wehreby I group on fc, id and main_group and get the sum of the value column.
My end df should look like:
> df
fc group_code id value main_group
1 F Egg_x 1 2 Egg
2 F Egg_y 1 21 Egg
3 F Egg 1 23 Egg
4 E Egg_x 1 4 Egg
5 E Egg_y 1 3 Egg
6 E Egg 1 7 Egg
7 TF Egg_x 1 20 Egg
8 TF Egg_y 1 15 Egg
9 TF Egg 1 35 Egg
In the above df every third row the value element in a sum of the previous two elements.
Thanks