[R] person-level to person-period xfm
David Winsemius
dwinsemius at comcast.net
Thu Nov 19 18:57:50 CET 2009
On Nov 19, 2009, at 12:23 PM, Richard M. Heiberger wrote:
> Robert Terwilliger wrote:
>> Dear R experts,
>>
>> I have a so-called person-level data frame that I need to transform
>> into a person-period data frame.
>>
>> If the lingo is unclear, the data have one row for each subject, with
>> repeated measures data each in a separate column.
>>
>> I need to transform these data so that each subject has multiple
>> rows,
>> one for each repeated measure value.
>>
>> Is there a quick-and-dirty way to do this transformation?
>>
>> Many thanks,
>>
>>
> There are several ways. This is one.
Here's another:
> data.frame(id=tmp$id, stack(tmp, select=-id))
id values ind
1 a 1 x1
2 b 2 x1
3 c 3 x1
4 a 4 x2
5 b 5 x2
6 c 6 x2
7 a 7 x3
8 b 8 x3
9 c 9 x3
10 a 10 x4
11 b 11 x4
12 c 12 x4
>
> > tmp <- data.frame(id=letters[1:3], x1=1:3, x2=4:6, x3=7:9, x4=10:12)
> > tmp
> id x1 x2 x3 x4
> 1 a 1 4 7 10
> 2 b 2 5 8 11
> 3 c 3 6 9 12
> > reshape(tmp, direction="long", varying=list(names(tmp)[-1]),
> ids="id")
> id time x1
> a.1 a 1 1
> b.1 b 1 2
> c.1 c 1 3
> a.2 a 2 4
> b.2 b 2 5
> c.2 c 2 6
> a.3 a 3 7
> b.3 b 3 8
> c.3 c 3 9
> a.4 a 4 10
> b.4 b 4 11
> c.4 c 4 12
> >
>
> ______________________________________________
> 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.
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list