I have data that I separated within a dataframe by item description and type. The separations are blank rows but I would like to fill the blank rows in with the sums of numeric values by each description and, if possible, add another blank row below the sums. Preferably, I would not need to sum the sections of data that only contain one row - see variable desc "a" but not a big deal if I do get a sum there.
This is an example of what I have now:
desc type xvalue yvalue
1 a z 16 1
2
3 b y 17 2
4 b y 18 3
5
6 c x 19 4
7 c x 20 5
8 c x 21 6
9
10 d x 22 7
11 d x 23 8
12
13 d y 24 9
14 d y 25 10
What I am looking for is output that looks similar to this.
desc type xvalue yvalue
1 a z 16 1
2
3 b y 17 2
4 b y 18 3
5 35 5
6
7 c x 19 4
8 c x 20 5
9 c x 21 6
10 40 15
11
12 d x 22 7
13 d x 23 8
14 45 15
15
16 d y 24 9
17 d y 25 10
18 49 19
I found an answer on how to do this in a column but not a row. Adding column of summed data by group with empty rows with R
I used acylam's dplyr answer to this question Add blank rows in between existing rows to create the empty rows. I changed the code slightly to fit my data better so my code is:
library(dplyr)
df %>%
split(df$id, df$group) %>%
Map(rbind, ., "") %>%
do.call(rbind, .)
I am hoping I can just add options to the do.call(rbind...) dplyr code I have above.