[R] paste name in for loop?

Duncan Murdoch murdoch at stats.uwo.ca
Tue Dec 1 01:53:52 CET 2009


On 30/11/2009 7:49 PM, Douglas M. Hultstrand wrote:
> Hello,
> 
> I am trying to create subsets of grouped data (by area size), and use 
> the area size as part of the output name.  The code below works for area 
> (xout) 1 and 50, the other files are given NA for an area.
> 
> A simple example:
> xout <- c(1,5,10,25,50,100)
> for(i in xout) { print(paste("Areal_Ppt_",xout[i],"sqmi.txt", sep="")) }

Your loop loops over the values in xout, so no need for xout[i].  You 
should be using

for(i in seq_along(xout))

if you want the indices, or just use i instead of xout[i] in the paste.

Duncan Murdoch

> [1] "Areal_Ppt_1sqmi.txt"
> [1] "Areal_Ppt_50sqmi.txt"
> [1] "Areal_Ppt_NAsqmi.txt"
> [1] "Areal_Ppt_NAsqmi.txt"
> [1] "Areal_Ppt_NAsqmi.txt"
> [1] "Areal_Ppt_NAsqmi.txt"
> 
> The actual code and partial dataset are below.
> 
> Thanks for your help,
> Doug
> 
> ###############
> ### Real Code ###
> ###############
> data2 <- read.table("GROUP.txt", header=T, sep=",")
> xout <- c(1,5,10,25,50,100)
> for(i in xout) {
>     name <- paste("Areal_Ppt_",xout[i],"sqmi.txt", sep="")
>     b.1 <- subset(data2, area == i)
>     write.table(b.1, file=name,quote=FALSE,row.names=FALSE, sep=",")
> }
> 
> ######################
> ### Dataset GROUP.txt ###
> #######################
> hr,area,avg_ppt
> 21,1,0
> 21,5,0.001
> 21,10,0.001
> 21,25,0.005
> 21,50,0.01
> 21,100,0.011
> 22,1,0.003
> 22,5,0.005
> 22,10,0.00824
> 22,25,0.04258
> 22,50,0.057
> 22,100,0.101
> 23,1,2.10328
> 23,5,2.02755
> 23,10,1.93808
> 23,25,1.78408
> 23,50,1.67407
> 23,100,1.568
> 24,1,3.20842
> 24,5,3.09228
> 24,10,2.95452
> 24,25,2.71661
> 24,50,2.54607
> 24,100,2.38108
>




More information about the R-help mailing list