[R] paste name in for loop?

jim holtman jholtman at gmail.com
Tue Dec 1 01:54:41 CET 2009


Here is what you want:

xout <- c(1,5,10,25,50,100)
for(i in xout) { print(paste("Areal_Ppt_",i,"sqmi.txt", sep="")) }

Notice that 'i' will be assigned each value in xout; you do not have
to index into the vector.  Notice that you second value is 50 which is
xout[5].

On Mon, Nov 30, 2009 at 7:49 PM, Douglas M. Hultstrand
<dmhultst at metstat.com> 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="")) }
> [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
>
> --
> ---------------------------------
> Douglas M. Hultstrand, MS
> Senior Hydrometeorologist
> Metstat, Inc. Windsor, Colorado
> voice: 970.686.1253
> email: dmhultst at metstat.com
> web: http://www.metstat.com
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?




More information about the R-help mailing list