[R] splitting a data.frame
Thomas Lumley
tlumley at u.washington.edu
Tue Jan 22 17:58:01 CET 2002
On Tue, 22 Jan 2002, Gary Collins wrote:
> I have the following (simple!?) problem which I am unable to find a
> relatively trivial solution to.
> If I have a dataframe,
>
> A 1
> A 7
> B 4
> B 5
> C 3
> D 3
> D 2
> E 5
> F 5
> F 6
>
> I would like to create a new data.frame in the form
>
> ID pt1 pt2
> A 1 7
> B 4 5
> C 3 NA
> D 3 2
> E 5 NA
> F 5 6
>
In addition to the specific suggestions already given there is a general
solution to this sort of problem with reshape()
You would need to create a time variable to indicate which is the first
or second observation, which in your case could be
df$time<-c(0,df$ID[-1]==df$ID[-10])
then
newdf<-reshape(df,timevar="time",idvar="ID",direction="wide")
In your case this isn't a big saving over the other approaches. It becomes
really useful when you have many variables, especially if some are
constant over time and others aren't.
-thomas
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list