s-news
[Top] [All Lists]

Re: Selecting data from a data frame

To: "'Data Analytics Corp.'" <dataanalytics@earthlink.net>, <s-news@lists.biostat.wustl.edu>
Subject: Re: Selecting data from a data frame
From: "Alan Hochberg" <alan.hochberg@prosanos.com>
Date: Tue, 11 Nov 2008 08:37:01 -0500
In-reply-to: <491981D3.9010601@earthlink.net>
References: <491981D3.9010601@earthlink.net>
Thread-index: AclD/XZ11nXKmXPGTTCWgUvZ95IuBwABHDwA
Walt,

This could probably be made more compact but it works, as long as max(year)
is unique for each isocode:

example <- function() {
        theData <-data.frame( isocode=c("usa", "usa", "usa", "usa", "usa",
                "usa", "can","can","gbr"), year=c(1990,1991,1992,1993,
                1994,1995,1992,1993,1997), pop=c(10,12,15,13,16,17,5,6,15))
        unique.isocode <- unique(theData$isocode)
        m <- length(unique.isocode)
        max.year <- as.vector(sapply(unique.isocode,function(x,theData) {
                max(theData$year[theData$isocode==x])
                },theData))
        pop.max.year <- as.vector(sapply(1:m, function(i, theData,
                unique.isocode, max.year) {
                theData$pop[theData$isocode==unique.isocode[i] &
                theData$year==max.year[i]]
        },theData, unique.isocode, max.year))
        data.frame(isocode=unique.isocode, year=max.year, pop=pop.max.year)
}

Alan

Alan Hochberg
VP, Research
ProSanos Corporation
225 Market St. Ste. 502, 
Harrisburg, PA 17101
Tel 717-635-2124 * Fax 717-635-2575



<Prev in Thread] Current Thread [Next in Thread>