Search code examples
rdplyrsapply

How to paste rows with same ID behind each other in r


this is probably a easy question but I can't find the answer anywhere :( so could you please help me?

If have a data frame that looks like this:

 "ID"      "date" 
  A       01-03-2017
  A       05-02-2016
  B       08-03-2016
  A       09-11-2012
  B       02-03-2014
  B       09-07-2013
  C       23-08-2016
  B       24-05-2017
  C       12-12-2015

and I want it to look like this: `

"ID"      "date.1"  "date.2"  "date.3"   "date.4"                                    
A       01-03-2017  05-02-2016  09-11-2012  NA 
B       08-03-2016  02-03-2014  09-07-2013 24-05-2017
C       23-08-2016  12-12-2015  NA          NA

So paste all the rows with the same ID behind each other, creating a new column for every row. I hope I make myself clear. Can someone please tell me how to do this? many many thanks in advance, Sara


Solution

  • Here is a solution by using 'spread' function. Thanks Markus

    # Libraries
    library(tidyverse)  
    
    # 1. Data set
    df <- data.frame(
      id = c("A", "A", "B", "A", "B", "B", "C", "B", "C"),
      date = c("01-03-2017", "05-02-2016", "08-03-2016", "09-11-2012",
           "02-03-2014", "09-07-2013", "23-08-2016", "24-05-2017", "12-12-2015"))
    
    # 2. New feature 'value' the same as 'date'
    df$value <- df$date
    
    # 3. Use 'spread' from 'tidyverse'
    
    # 3.1. Just 'spread'
    spread(df, key = date, value = value)
    
    # 3.2. 'spread' thanks 'Markus' for the solution
    df %>% 
      group_by(id) %>% 
      mutate(date = seq_along(id)) %>% 
      spread(key = date, value = value, sep = ".") 
    

    Hope it helps in some way