Search code examples
rfunctionaggregate

collapse text by 2 ID's in a row


I have a question similar to this topic: "Collapse text by group in data frame [duplicate]"

group text
a a1
a a2
a a3
b b1
b b2
c c1
c c2
c c3
c c4

I would like to collapse by two sequential ID's (not the whole ID group)

group text
a a1a2
a a2a3
b b1b2
c c1c2
c c2c3
c c3c4

Solution

  • Alternative tidyverse answer:

    library(tidyverse)
    dat %>%
      group_by(group) %>%
      mutate(text=paste0(lag(text),text)) %>% slice(-1)
    

    Using data.table:

    library(data.table)
    setDT(dat)
    dat[, paste0(shift(text,1), text)[-1], by=group]
    
    #   group   V1
    #1:     a a1a2
    #2:     a a2a3
    #3:     b b1b2
    #4:     c c1c2
    #5:     c c2c3
    #6:     c c3c4