[R] Reshape from long to wide format with date variable

Joshua Wiley jwiley.psych at gmail.com
Wed Jul 6 19:05:49 CEST 2011


Hi Pete,

Try the reshape function (see ?reshape for documentation).  It can be
a bit confusing, but its worth learning if you deal with multiple
observations per unit much.  Code inline does what you want (though
you might need a bit of tweaking to get pretty names, etc.

HTH,

Josh

On Wed, Jul 6, 2011 at 6:40 AM, Pete Pete <noxyport at gmail.com> wrote:
> Hi,
>
> I need to reshape my dataframe from a long format to a wide format.
> Unfortunately, I have a continuous date variable which gives me headaches.
>
> Consider the following example:
>> id=c("034","034","016","016","016","340","340")
>> date=as.Date(c("1997-09-28", "1997-10-06", "1997-11-04", "2000-09-27",
>> "2003-07-20", "1997-11-08", "1997-11-08"))
>> ref=c("2","2","1","1","2","1","1")
>> data1=data.frame(id,date,ref)

## create time variable
data1$time <- with(data1, ave(1:nrow(data1), id, FUN = seq_along))

wdata1 <- reshape(data1, idvar = "id", timevar = "time", direction = "wide")
> wdata1
   id     date.1 ref.1     date.2 ref.2     date.3 ref.3
1 034 1997-09-28     2 1997-10-06     2       <NA>  <NA>
3 016 1997-11-04     1 2000-09-27     1 2003-07-20     2
6 340 1997-11-08     1 1997-11-08     1       <NA>  <NA>



>> data1
>   id       date ref
> 1 034 1997-09-28   2
> 2 034 1997-10-06   2
> 3 016 1997-11-04   1
> 4 016 2000-09-27   1
> 5 016 2003-07-20   2
> 6 340 1997-11-08   1
> 7 340 1997-11-08   1
>
>
> I would like to have it like this:
>> data2
>   id      date1      date2      date3 ref1 ref2 ref3
> 1 034 1997-09-28 1997-10-06         NA    2    2   NA
> 2 016 1997-11-04 2000-09-27 2003-07-20    1    1    2
> 3 340 1997-11-08 1997-11-08         NA    1    1   NA
>
> All I tried the reshape package but ended up in multiple variables for each
> of the dates and that is not what I would like to have.
>
> Thanks for you help.
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Reshape-from-long-to-wide-format-with-date-variable-tp3648833p3648833.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list