[R] by output into data frame

David Perlman dperlman at wisc.edu
Mon Mar 19 22:44:34 CET 2012

I could do this in various hacky ways, but what's the right way?

I have a nice application of the by function, which does what I want.  The output looks like this:

> auc_stress
lab.samples.stress$subid: 2
  cortisol amylase
1   919.05  6834.8
lab.samples.stress$subid: 3
   cortisol  amylase
11   728.25 24422.05


What I want is a data frame roughly like this:

subid  cortisol.auc  amylase.auc
2      919.05        6834.8
3      728.25        24422.05


What is a nice way to make that happen?

Here is the code and data that I am using, which should run directly if you copy and paste it:

sanity.check<-read.csv("http://brainimaging.waisman.wisc.edu/~perlman/testdata.csv", header=TRUE, sep = ",")
lab.samples <- subset(sanity.check,Sample!='before bed' & Sample!='morning after')

auc_ground <- function(sub_df) {
	for (i in 1:(nrow(sub_df)-1) ) {

auc_stress<-by(lab.samples.stress[c('cortisol','amylase')], lab.samples.stress$subid, auc_ground, simplify=T)
auc_control<-by(lab.samples.control[c('cortisol','amylase')], lab.samples.control$subid, auc_ground, simplify=T)

Thanks for your help!

P.S. sorry if this question has been answered before, it is nearly impossible to get useful google results on search terms like "by"...  too common word...

A neuroscientist is at the video arcade, when someone makes him a $1000 bet
on Pac-Man. He smiles, gets out his screwdriver and takes apart the Pac-Man
game. Everyone says "What are you doing?" The neuroscientist says "Well,
since we all know that Pac-Man is based on electric signals traveling
through these circuits, obviously I can understand it better than the other
guy by going straight to the source!"

More information about the R-help mailing list