Something like this should work ... this function probably exists somewhere
in S+ or a related library ...
> stackDf <- function(df, repCols, stackCols = setdiff(names(df), repCols),
groupColName = "Group", newColName = "Value")
{
if(mode(repCols) != "character")
repCols <- names(df)[repCols]
N <- length(myVec <- unlist(df[, stackCols]))
outDf <- cbind(df[rep(1:nrow(df), length = N), repCols],
rep(stackCols, each = nrow(df)), myVec)
names(outDf) <- c(repCols, groupColName, newColName)
outDf
}
> myData <- data.frame(matrix(rnorm(800), nrow = 100))
> dos.time(stackDf(myData, 1:7, groupColName = "Period"))
[1] 0.02
Rich.
mangosolutions
S and R Consulting and Training
Tel +44 118 902 6617
Fax +44 118 902 6401
-----Original Message-----
From: s-news-owner@lists.biostat.wustl.edu
[mailto:s-news-owner@lists.biostat.wustl.edu] On Behalf Of Alejandro Munoz
Sent: 24 June 2005 15:13
To: s-news@lists.biostat.wustl.edu; b.jacobs@pandora.be; rmh@temple.edu
Subject: Re: [S] Stack Column Question
Bert,
Sounds like a job for reshape(). I must add that lately I've been using
R exclusively, so it is possible reshape() may not exist in S-PLUS. See
also ?stack, which, again, may exist only in R.
We can be more helpful if you give us a small example of what the
original and desired data frames look like.
Hope this helps.
alejandro
>>> "Bert Jacobs" <b.jacobs@pandora.be> 6/24/2005 8:53:38 AM >>>
Fast Solution but I how do I repeat columns 1:4, stack columns 5:164
into a column "Data" and create a group column "Period" with the
colnames.
-----Original Message-----
From: s-news-owner@lists.biostat.wustl.edu
[mailto:s-news-owner@lists.biostat.wustl.edu] On Behalf Of Richard M.
Heiberger
Sent: 24 June 2005 15:31
To: Bert Jacobs; s-news@lists.biostat.wustl.edu
Subject: Re: [S] Stack Column Question
> tmp <- data.frame(matrix(0,3600,164))
> date()
[1] "Fri Jun 24 09:29:49 EDT 2005"
> tmp2 <- unlist(tmp[,1:160])
> date()
[1] "Fri Jun 24 09:29:53 EDT 2005"
> length(tmp2)
[1] 576000
>
4 seconds
--------------------------------------------------------------------
This message was distributed by s-news@lists.biostat.wustl.edu. To
unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu with
the BODY of the message: unsubscribe s-news
--------------------------------------------------------------------
This message was distributed by s-news@lists.biostat.wustl.edu. To
unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu with
the BODY of the message: unsubscribe s-news
--------------------------------------------------------------------
This message was distributed by s-news@lists.biostat.wustl.edu. To
unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu with
the BODY of the message: unsubscribe s-news
|