# R: Loop pairs of columns in a dataframe

Is it possible to plot pairs of columns in a single plot with a loop? For example, if I have a data frame of time series with 10 columns (x1, x2.. x10), I would like to create 5 plots: 1st plot will display x1 and x2, the 2nd plot would display x3 and x4 and so on.

Any plotting method would be useful, (zoo, lattice, ggplot2).

I got stuck at creating a loop to plot a single variable:

set.seed(1) x<- data.frame(replicate(10,rnorm(10, mean = 0, sd = 1))) cols <- seq(1,10) library(zoo) z <- read.zoo(x) for (i in cols) { plot(z[,i], screen = 1) }

Thanks in advance.

## Answers

How about this with ggplot2 and reshape2:

require(reshape2) require(ggplot2) m<-melt(matrix(z,10)) m$facet<-cut(m$Var2,c(0,2,4,6,8,10)) ggplot(m)+geom_line(aes(x=Var1,y=value,group=Var2,color=factor(Var2)))+facet_wrap(~ facet)

It can be done in a single line without a loop like this where the col argument specifies that the odd series are black and the even are red. Note that z in the question has 9 columns (since the first column in x is the time index) so we have used a 10 column z below instead which was likely what was intended.

library(zoo) # test data set.seed(123); z <- zoo(matrix(rnorm(250), 25)); colnames(z) <- make.names(1:10) plot(z, screen = rep(colnames(z)[c(TRUE, FALSE)], each = 2), col = 1:2)

The output is shown below. To produce a single column add the argument nc=1 or to produce a lattice plot replace plot with xyplot.

ADDED: lattice solution.

like this? Although I am not clear how you want to plot it.

par(mfrow=c(1,5)) for (i in seq(1,10,by=2)){ plot(x[,i],x[,i+1]) }

### Need Your Help

### Getting accurate referrals from arbitrary sites analytics.js

google-analytics cross-domain google-analytics-api analytics.js

Working on a web app where at step 2 the user leaves to her domain and comes back. The domain she leaves to is dynamically entered into our form (this step is required for an OAuth token flow).