[R] use variable in for loop to name output files

MacQueen, Don macqueen1 at llnl.gov
Wed Dec 12 16:29:52 CET 2012


If your final goal is to write the csv files, and only the csv files, then
then this (not tested) should do it.

for (i in unique(appended$dp) ) {
  tmp <- subset(appended, dp==i & sampled==0)
  write.table(tmp,
    file= file.path('output', paste0('set',i,'.csv')),
    sep=',',
    row.names=FALSE)
}

I threw in the use of file.path(); not necessary, but will make your
scripts more cross-platform.

And you don't actually have to create the 'tmp' data frame. You could
do this inside the loop:

write.table(
  subset(appended, dp==i & sampled==0),

  file= file.path('output', paste0('set',i,'.csv')),
  sep=',',
  row.names=FALSE)


But I often find nested function calls harder to read.
 
David and Rui both suggested storing the subsets in a list, and I agree.

But if you really want objects named "set1", "set2", and so on in your
workspace, so that you can reference them by those names, then you need
the assign function. Experience will eventually give you some ideas
of which way is better and when. The general recommendation is to avoid
using assign(), and that's good advice. But I do occasionally find it
useful.

-Don


-- 
Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062





On 12/10/12 1:03 PM, "john-usace" <john.r.kucharski at usace.army.mil> wrote:

>Hi,
>
>This question should be simple to answer. I am a new R user.
>
>I have a data.frame called appended. I would like to break it into 7
>smaller
>datasets based on the value of a categorical variable dp (which has values
>1:7). I would like to name the smaller datasets set1, set2,
>set3,....,set7.
>I don't know how to refer to the variable in the for loop, when naming the
>output datasets. In STATA (which I am much more familiar with) each i in
>the
>foreach loop would be refered to as `i'. This is the code I've included
>below. I've also tried set[[i]] and set[i] neither works.
>
>for (i in 1:7) {
>	set`i' = appended[which(appended$dp==i & appended$sampled==0), ]
>	write.table(set`i', file = "output\\set`i'.csv", sep = ",", row.name=F)
>	}
>
>I'm assuming I just need to replace `' with something else but I can
>figure
>out what that something else is.
>
>
>
>--
>View this message in context:
>http://r.789695.n4.nabble.com/use-variable-in-for-loop-to-name-output-file
>s-tp4652711.html
>Sent from the R help mailing list archive at Nabble.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.




More information about the R-help mailing list