0

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

Alaleh
  • 1,008
  • 15
  • 27
  • 1
    Try this `library(tidyverse); df %>% group_by(ID) %>% mutate(value = date, date = seq_along(ID)) %>% spread(key = date, value = value, sep = ".")` where `df` is the name of your data set. – markus May 19 '18 at 09:54

1 Answers1

0

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

Andrii
  • 2,843
  • 27
  • 33