Search code examples
rmergedatatableplyrorganization

How do I dissolve repeating data and add a column to my data frame summing the quantity dissolved in r?


I need help on how to dissolve multiple columns based on a commonality in r, and also adding a new column to the data frame that reflects the quantity dissolved. I didn't include in the mock data below, but the y and z data are different in every column. I have hundreds of rows too.

#My data now

x  y  z  

A
A
A
A
B
B
B
B
B
B
C
C
C
C
C

#How I want my data to look
x  y  z  q

A        4
B        6
C        5


Solution

  • You can use dplyr to group, then count the number of entries within each group and place into a new column using summarise:

    library(dplyr)
    df %>%
      group_by(x) %>%
      summarise(q = n())