 <p>We could use <code>data.table</code>. Convert the 'data.frame' to 'data.table' (<code>setDT(df1)</code>), create a new grouping variable by using <code>%/%</code> based on the values in 'A'. Then, grouped by 'A1', we get the <code>sum</code> of 'B' and also <code>paste</code> the <code>unique</code> elements in 'A' together. If not needed, the grouping variable 'A1' can be assigned to NULL.</p> <pre><code>library(data.table) setDT(df1)[, A1:= (A-1)%/%2 +1][, list(A= paste0("A",paste(unique(A), collapse="-")), B= sum(B)) ,A1][,A1:= NULL][] # A B #1: A1-2 4 #2: A3-4 9 </code></pre>