Use "lines" command with a vector of objects in R

157 views Asked by At

I'm using R to analyze IR-spectras. What I'm trying to do is to make a list or vector of objects, in this case Spectras, and plot them into the same "window". I used the command plot(Spectrum1,...) for the first Spectrum and the commands

lines(Spectrum2,...) 
lines(Spectrum3,...) 
...

for the following Spectras. This worked well, but I was wondering if I could make a list or a vector of the Spectras, like

Spectras <- c(Spectrum2, Spectrum3,...)

or

Spectras <- list(Spectrum2, Spectrum3,...)

and plot them in one command line, like:

lines(Spectras,..)

In case of a list, R says

'x' is a list, but does not have components 'x' and 'y'

If I do it with the c() command it just plots the Spectras one behind another.

Some ideas, how to get this to work?

1

There are 1 answers

0
Nick Kennedy On

Use a list and then lapply or plyr::l_ply functions. If list of spectra is called "Spectra" with each component a matrix or data frame with columns x and y:

lapply(Spectra, lines)

Or

plyr::l_ply(Spectra, lines)

Alternatively, use ggplot2:

library("ggplot2")
library("plyr")
SpecDf <- as.data.frame(do.call("rbind", Spectra))
SpecDf$SpectrumNumber <- rep(1:length(Spectra), plyr::laply(Spectra, nrow))
ggplot(SpecDf, aes(x = x, y = y, colour = SpectrumNumber)) + geom_line()