[R] how to loop through names ?

Duncan Murdoch dmurdoch at pair.com
Mon Mar 22 17:42:23 CET 2004


On Sat, 06 Mar 2004 09:52:31 +0000, "Pete Phillips" <pete at smtl.co.uk>
wrote :

>sales<-read.table("sales.dat",header=TRUE);
...

>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!).

I think your indexing is off a bit.  "sales" is a data frame, so
something like sales[13:24, "an"] would select some rows from the
column named "an".  

Thus sales[13:24, names(sales)[i]] would work, or even more simply
sales[13:24, i].

You don't often need the double bracket indexing "[[i]]".  It is used
with lists, to select the element; names(sales) is a vector, not a
list, so it only needs single brackets.

Duncan Murdoch




More information about the R-help mailing list