-1

I have a time-series of events:

time <-c("01-01-1970","01-01-1971","01-01-1971","01-01-1972")
event <-c("A","A","B","B")

df <- data.frame(time, event)

time event
1 01-01-1970     A
2 01-01-1971     A
3 01-01-1971     B
4 01-01-1972     B

Now, I would like to put events that happen at the same time in one line. In my example that would be rows 2 and 3. The outcome should look like this:

time event

1 01-01-1970     A
2 01-01-1971     A & B
4 01-01-1972     B

Any ideas how to do this?

Best, Felix

Felix
  • 309
  • 2
  • 12
  • 1
    Check the group by and `paste` i.e. `aggregate(event~time, df1, FUN = paste, collapse= " & ")` – akrun Aug 18 '17 at 08:24
  • 1
    In the `data.table way` it would be : `setDT(df)[, .(new_col = paste0(event, collapse = " & ")), by = time]` – Mbr Mbr Aug 18 '17 at 08:26

1 Answers1

2

You can use aggregate:

aggregate(df$event,by=list(df$time),FUN= paste,collapse = " & ")
Orhan Yazar
  • 909
  • 7
  • 19