[S] Transforming the structure of a data frame

HumboltA@kochind.com
Thu, 10 Sep 1998 14:14:48 -0500


Suppose I have a data frame called mydat that looks like
Year County Yield
1 97 Bu 20
2 97 Sg 25
3 97 Su 27
4 98 Bu 30
5 98 Sg 35
6 98 Su 37

I want to change it to a data frame that looks like
Year BuCoYield SgCoYield SuCoYield
1 97 20 25 27
2 98 30 35 37

Does anyone know of a flexible Splus function or library to make this type
of restructuring of the data?
I can solve this particular problem. One way (likely poor) is shown below.
But I wonder if anyone has already faced problems like this and developed
very flexible function(s) to handle some of the ways we might wish to
restructure data frames in Splus.

Thanks.

Allen Humbolt
Quantitative Analyst
Koch Industries
HumboltA@kochind.com

> WideFn(mydat$Year, mydat$County, mydat$Yield) # the function call

WideFn <- function(Time, Location, Result)
{
MyYear <- unique(Time)
MyCounties <- unique(Location)
MyYields <- matrix(nrow = length(MyYear), ncol = length(MyCounties))
for(i in 1:length(MyCounties)) MyYields[, i] <- Result[Location ==
MyCounties[i]]
AllData <- data.frame(Year = MyYear, MyYields)
for(i in 1:length(MyCounties)) names(AllData)[i + 1] <-
paste(as.character(MyCounties[i]), "CoYield", sep = "")
AllData
}

-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news