I have the following df:
df <- read.table(text="col1 col2 col3
1 pepe 12
2 juan 2
3 rojo 33
4 rojo 44
5 azul 45
6 azul 5
7 amarillo 100
8 amarillo 200
9 amarillo 150
10 rojo 200
11 azul 25
12 amarillo 23
13 azul 50", header=TRUE, stringsAsFactors=FALSE)
and I would like to group it by the id column, but only some cases, for example ids 3,4, and 10 on the one hand, and 7,8,9,12 on the other. so that it would be
col1 col2 col3
1 pepe 12
2 juan 2
3,4,10 rojo 277
5 azul 45
6 azul 5
7,8,9,12 amarillo 473
11 azul 25
13 azul 50
I don't know if you can group by column indicating the rows.
What you can do is generate a new column based on the criteria you handle, one way could be indicating the
id
particular ones that should be "joined":The other would be using "color" as an alternative grouping group, only in the case of certain colors:
One option is to use the library
dplyr
, but to get the same result you want, you have to group the values of col1 based on the conditions you describe, and put this result in a new column. And then with the functiongroup_by
you can group the values of the col3 into a new updated col3 and deleting the old one.OUTPUT:
With a little more code, the result remains in the same table that you describe: