Re: [R] reshaping data frame

From: John Kane <jrkrideau_at_yahoo.ca>
Date: Thu, 21 Feb 2008 10:08:51 -0500 (EST)


Here is a very clumsy way to do it but I think it works

fact1 <- rep("level.1", length(mydat[,1])) fact2 <- rep("level.2", length(mydat[,1]))

lels <- c(fact1,fact2)
nams <- c("indiv", "case.id", "covar")
set1 <-  mydat[, c(1,2,3)] ; names(set1) <- nams 
set2 <-  mydat[,c(1, 4,5)] ; names(set2) <- nams

newdata <- cbind(lels, rbind(set1,set2)) mydata <- rbind(newdata[, c(2,1,4,3)], newdata[, c(2,1,4,3)])
 names(mydata) <- c("indiv", "factor", "covar", "caseid")
mydata[order(mydata$indiv, mydata$caseid, mydata$factor),]

> Dear all,
>
> I'm having a few problems trying to reshape a data
> frame. I tried with
> reshape{stats} and melt{reshape} but I was missing
> something. Any help is
> very welcome. Please find details below:
>
> #################################
> # data in its original shape:

>
> indiv <- rep(c("A","B"),c(10,10))
> level.1 <- rpois(20, lambda=3)
> covar.1 <- rlnorm(20, 3, 1)
> level.2 <- rpois(20, lambda=3)
> covar.2 <- rlnorm(20, 3, 1)
> my.dat <-
> data.frame(indiv,level.1,covar.1,level.2,covar.2)
>
> # the values of level.1 and level.2 represent the
> number of cases for the
> particular
> # combination of indiv*level*covar value
>
> # I would like to do two things:
> # 1. reshape to long reducing my.dat[,2:5] into two

> colums "factor" (levels=
> level.1 & level.2)
> # and the covariate
> # 2. create one new row for each case in level.1 and
> level.2
>
> # the new reshaped data.frame would should look like
> this:
>
> # indiv factor covar case.id
> # A level.1 4.614105 1
> # A level.1 4.614105 2
> # A level.2 31.064405 1
> # A level.2 31.064405 2
> # A level.2 31.064405 3
> # A level.2 31.064405 4
> # A level.1 19.185784 1
> # A level.2 48.455929 1
> # A level.2 48.455929 2
> # A level.2 48.455929 3
> # etc...
>
> #############################
>
> Thank you very much!!
>
> Ahimsa
>
>
> --
> ahimsa campos-arceiz
> www.camposarceiz.com
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



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. Received on Thu 21 Feb 2008 - 15:12:54 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 21 Feb 2008 - 16:30:15 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive