[R] Looping over groups

Dylan Beaudette dylan.beaudette at gmail.com
Wed Aug 20 21:57:50 CEST 2008


On Wednesday 20 August 2008, Josh B wrote:
> > Works for me:
> > x <- read.csv('christina.txt')
> >
> > x.list <- by(x, x$gen, function(d) {
> > d.clean <- d[,-1]
> > cov(d.clean, y= NULL, use= "complete.obs", method="pearson")
> > } )
> >
> >note that the output is a list, where each element corresponds to one
> >level of 'gen'. if you need to write each element out to a file, see
> >?sapply or ?lapply .
>
> Yes, how would I do that? The usage of sapply is pretty hard to understand,
> at least at first glance, and I have never played with it before.
>
> I will need to output all of the covariance matrices to one CSV or text
> file (there's probably some sort of "append = TRUE" argument involved).
>
> Does anyone know how to do this easily?

very quickly I would try something like:

# will write to the screen
lapply(x.list, write.csv)

# you will probably want something more interesting:
lapply(x.list, function(element_i)
{
# get level of 'gen' from list element

# make a filename, see ?paste

# write out a file for each
write.table(element_i, file=filename, row.names=FALSE, ...)

}

)


-- 
Dylan Beaudette
Soil Resource Laboratory
http://casoilresource.lawr.ucdavis.edu/
University of California at Davis
530.754.7341



More information about the R-help mailing list