Marcos
Marcos

Reputation: 1

Transpose and create new variables in R

I have a data frame with the following structure:

study_id date
1        01/01/2011
2        01/01/2012
2        01/01/2013
3        01/01/2014
3        01/01/2015
3        01/01/2016

I would like to change the data frame to:

study_id date_1      date_2    date_3
1        01/01/2011  NA         NA
2        01/01/2012  01/01/2013 NA
3        01/01/2014  01/01/2014 01/01/2016

Please note these dates are just examples, the date does not follow this order (01/01/2011 + 1 years and so goes on)

PS: Thanks webprogrammer for editing my question. I deleted before I noticed you fixed it.

Upvotes: 0

Views: 36

Answers (2)

Ben
Ben

Reputation: 30474

Here is a tidyverse approach:

library(tidyverse)

df %>%
  group_by(study_id) %>%
  mutate(row_id = row_number()) %>%
  pivot_wider(id_cols = study_id, values_from = date, names_from = row_id, names_prefix = "date_")

Output

# A tibble: 3 x 4
# Groups:   study_id [3]
  study_id date_1     date_2     date_3    
     <int> <chr>      <chr>      <chr>     
1        1 01/01/2011 NA         NA        
2        2 01/01/2012 01/01/2013 NA        
3        3 01/01/2014 01/01/2015 01/01/2016

Upvotes: 1

akrun
akrun

Reputation: 887038

We can use dcast from data.table

library(data.table)
dcast(setDT(df1), study_id ~ paste0("date_", rowid(study_id)), value.var = "date")
#study_id     date_1     date_2     date_3
#1:        1 01/01/2011       <NA>       <NA>
#2:        2 01/01/2012 01/01/2013       <NA>
#3:        3 01/01/2014 01/01/2015 01/01/2016

Upvotes: 1

Related Questions