[R] how to loop through names ?

Gabor Grothendieck ggrothendieck at myway.com
Mon Mar 22 18:21:49 CET 2004


Try this simplification which loops through the names
rather than their index and improves plot a bit too:

   ix <- 13:24
   for( n in names(sales) ) {
     fname <- paste( n, "ps", sep="." )
     postscript( file = fname )
     plot( sales[ix,"serial"], sales[ix,n], 
         xlab = "Month No", ylab = "No/month", main = n )
     dev.off()
   }

or use the subset= argument to plot.formula:

   plot( sales[,n] ~ sales$serial, subset = ix, 
            xlab = "Month No", ylab = "No/month",  main = n )

Date:   Sat, 06 Mar 2004 09:52:31 +0000 
From:   Pete Phillips <pete at smtl.co.uk>
To:   <r-help at stat.math.ethz.ch> 
Subject:   [R] how to loop through names ? 

 

Hi

I'm sure I'm missing something very straighforward here :-(

I have a data set 'sales' as follows:
==========================================
# read in the sales data
sales<-read.table("sales.dat",header=TRUE);
#generate a serial field
sales$serial=c(1:24)

sales

an l ml ne ni total serial
1 43 25 35 51 17 69 1
2 38 18 47 94 3 99 2
.......
24 58 13 41 95 4 1 24
===========================================

(extra rows and columns deleted).

I wish to produce a postscript plot file for each column plotted vs the
serial column, using either the 1st to 12th row or the 13th to 24th
rows, where the filename consists of the column name with '.ps' added.

This the code I have so far:

============================================
for (i in 1:(length(names(sales))-1)) {

fname <- paste(names(sales)[[i]],".ps",sep="")

postscript(file=fname)

plot(
sales$serial[13:24], 
sales[names(sales)[[i]]][13:24],
xlab="Month No", ylab="No/month")
dev.off()

}
==============================================

The filename generation works (yay!), but I think I have missed
something very basic here as that plot line seems too complex (and
doesn't work!).

Any ideas please ?

Pete




More information about the R-help mailing list